HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Correcting duplicate names in array

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
correctingduplicatearraynames

Problem

I have an array of file names. For example:

string[] files= { "one.zip", "two.txt", "one.zip", "three.txt", "three.txt", "one.zip" };


And I've developed the following method to correct duplicate names. What the method does is just change duplicate names. I am just adding incremented value for the next duplicated value. For example, my developed method ChangingDuplicateNames(string[] files)correct the previous array to:

string[] files= { "one.zip", "two.txt", "one1.zip", "three.txt", "three1.txt", "one2.zip"};


And implementation of ChangingDuplicateNames(string[] files) is:

```
private string[] ChangingDuplicateNames(string[] files)
{
//Creating a dicitonary to store duplicated values. "Key" of dictionary
//is duplicated name, "Value" of dictionary is number to add for name
Dictionary duplicateNames = files.GroupBy(x => x)
.Where(group => group.Count() > 1)
.ToDictionary(grouped => grouped.Key, grouped => 0);

if (duplicateNames.Count == 0)
return files;

int namesLength = files.Length;
string actualName = string.Empty;
for (int indexArray = 0; indexArray < namesLength; indexArray++)
{
int incrementedValue;
bool isDuplicate = duplicateNames.TryGetValue(files[indexArray],
out incrementedValue);
if (isDuplicate)
{
actualName = files[indexArray];
if (incrementedValue == 0)
files[indexArray] = files[indexArray];
else
{
//Adding increment to the mext duplicate name
string fileNameWithoutExtension = Path
.GetFileNameWithoutExtension(files[indexArray]);
string fileExtension = Path
.GetExtension(files[indexArray]);
files[indexArray] = fileNameWithoutExtension +
"(" + incrementedValue + ")" + fileExtension;
}
duplicateNames[actualName] = ++increment

Solution

A quick and easy way would be to use a HashSet and check the return of the Add() method. If it returns false you will know that you need to create a new filename. So let's start by extracting the creation of the filename like so

private string CreateFileName(string original, ref int counter)
{
    counter += 1;
    string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(original) + "(" + counter + ")";
    string fileExtension = Path.GetExtension(original);
    return fileNameWithoutExtension + fileExtension;
}


Next we iterate over all of the items of the array and try to add it to the HashSet. If we can't add it, we create the new filename and try to add it again until we succeed.

private string[] ChangingDuplicateNames(string[] files)
{
    var hashSet = new HashSet(StringComparer.OrdinalIgnoreCase);
    foreach (var file in files)
    {
        var currentFile = file;
        int counter = 0;
        while (!hashSet.Add(currentFile))
        {
            currentFile = CreateFileName(file, ref counter);
        }
    }

    return hashSet.ToArray();
}

Code Snippets

private string CreateFileName(string original, ref int counter)
{
    counter += 1;
    string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(original) + "(" + counter + ")";
    string fileExtension = Path.GetExtension(original);
    return fileNameWithoutExtension + fileExtension;
}
private string[] ChangingDuplicateNames(string[] files)
{
    var hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
    foreach (var file in files)
    {
        var currentFile = file;
        int counter = 0;
        while (!hashSet.Add(currentFile))
        {
            currentFile = CreateFileName(file, ref counter);
        }
    }

    return hashSet.ToArray();
}

Context

StackExchange Code Review Q#162577, answer score: 5

Revisions (0)

No revisions yet.