Search code examples
c#linqlambda

Append index number to duplicated string value in a list - by using Lambda


I have a IList<string>() which holds some string values, and there could be duplicated items in the list. What I want is to append a index number to end of the string to eliminate the duplication.

For example, I have these values in my list: StringA, StringB, StringC, StringA, StringA, StringB. And I want the result looks like: StringA1, StringB1, StringC, StringA2, StringA3, StringB2. I need to retain the original order in list.

Is there a way I can just use one Lambda expression?


Solution

  • You are looking for something like this:

    yourList.GroupBy(x => x)
            .SelectMany(g => g.Select((x,idx) => g.Count() == 1 ? x : x + idx))
            .ToList();
    

    Edit: If the element order matters, here is another solution:

    var counts = yourList.GroupBy(x => x).ToDictionary(x => x.Key, x => x.Count());
    
    var values = counts.ToDictionary(x => x.Key, x => 0);
    
    var list = yourList.Select(x => counts[x] > 1 ? x + ++values[x] : x).ToList();