Is this code good/efficient enough?

menthor

New member
Joined
Jan 30, 2017
Messages
1
Programming Experience
Beginner
Could you please tell me if there is something that can be changed here to make the code in the method better in any terms?



C#:
public static string GetUniqueName(List<string> existedNames, string name)
{
    name = Regex.Replace(name, @" \([0-9]+\)$", "");

    if (existedNames.Any(n => n == name) == false)
        return name;
    
    for (int j = 0; j < 1000; j++)
    {
        var newName = name + " (" + j + ")";
        if (existedNames.Any(n => n == newName) == false)
        {
            return newName;
        }
    }

    return "";
}

Any suggestions are welcome
 
Well, the code looks simple enough, but since Any() returns a boolean, you could leave out the "== false" and use negation.

C#:
public static string GetUniqueName(List<string> existedNames, string name)
{
    name = Regex.Replace(name, @" \([0-9]+\)$", "");

    if (!existedNames.Any(n => n == name))
        return name;
    
    for (int j = 0; j < 1000; j++)
    {
        var newName = name + " (" + j + ")";
        if (!existedNames.Any(n => n == newName))
        {
            return newName;
        }
    }

    return "";
}


I don't know that it's necessarily better.
 
Last edited:
Back
Top Bottom