Duplicate Strings – How to Find in C#

algorithmsccode-reviews

I allow my user to create profiles, meaning they potentially could create some with duplicate names. This can be problematic so I want to prevent them from doing so. I coded up this first pass recursive-ish algorithm for detecting what number copy I should assign to the Name, however I'm almost certain there is a better way to write it, but my writers block has dropped the hammer down on me–in fact, I wasn't even sure how to word the question or Google something that might already exist. Here is the code:

//Check to see if there is another profile with the same name
var exiProf = profiles.FirstOrDefault(p => p.Name == newProf.Name);
int counter = 1;
while (exiProf != null)
{
    // Only match with the last number surrounded with parens
    Regex exp = new Regex(@"\((\d)\)$");
    Match ma = exp.Match(exiProf.Name);
    if(ma.Success)
    {
        num = int.Parse(ma.Groups[1].Value);
        var numChar = (counter).ToString();
        var nextNumChar = ( ++counter).ToString();
        newProf.Name = newProf.Name.Replace(numChar, nextNumChar);

        //Loop to make sure new name doesn't already exist
        exiProf = profiles.FirstOrDefault(p => p.Name == newProf.Name);
    }
    else
    {
        newProf.Name += " (" + num + ")";

        //Loop to make sure new name doesn't already exist
        exiProf = profiles.FirstOrDefault(p => p.Name == newProf.Name);
    }
}

profiles.Add(newProf);

Meaning, if I try to add "New", "New", "New", "New" in that order, "New (1)", "New (2)", "New (3)", "New (4)" is what shows up in my list.

Note: I have tagged algorithms in here because I am capable of turning pseudocode into C#.

Best Answer

I would think this will do it:

if (profiles.Any(p => p.Name == newProf.Name))
{
    string template = newProf.Name + " ({0})";
    int counter = 1;
    string candidate = String.Format(template, counter);

    while (profiles.Any(p => p.Name == candidate))
    {
        counter++;
        candidate = String.Format(template, counter);
    }

    newProf.Name = candidate;
}
Related Topic