Search code examples
c#linqgroup-by

Check for unique values in a list, and then increment the duplicates c# Linq


I have a situation where I want to enumerate over a list of strings, and then check for duplicates and increment the number at the end if there are any duplicates present. The order of the strings is irrelevant.

E.g if my list is:

  • Test
  • Tester
  • Tester
  • Tester

It would be changed to

  • Test
  • Tester
  • Tester (1)
  • Tester (2)

Is there an easy way to do this? My current thoughts are to do a group by, and then find the count of each group and then recursively go over each group and change the values - but sure there is a quicker way to do this using LINQ


Solution

  • You can use the overload of Select that projects the index:

    List<string> resultList = list
        .GroupBy(s => s)
        .SelectMany(g => g
          .Select((s, index) => $"{s}{(index == 0 ? "" : $" ({index})")}"))
        .ToList();
    

    Update: If you want to maintain the original order as commented, so not group duplicates together but A,B,A => A,B,A1, then you can use this:

    Dictionary<string, int> dupcounter = new();
    List<string> resultList = new(list.Count);
    foreach(string s in list)
    {
        dupcounter.TryGetValue(s, out int n);
        dupcounter[s] = ++n;
        resultList.Add(n > 1 ? $"{s} ({n-1})" : s);
    }
    

    Demo: https://dotnetfiddle.net/W7XQTb