Search code examples
c#linqduplicatesstring-comparison

Get duplicates from list case insensitive


List<string> testList = new List<string>();
testList.Add("A");
testList.Add("A");
testList.Add("C");
testList.Add("d");
testList.Add("D");

This query is case sensitive:

// Result: "A"
List<String> duplicates = testList.GroupBy(x => x)
                                  .Where(g => g.Count() > 1)
                                  .Select(g => g.Key)
                                  .ToList();

How would it look case insensitive? (Result: "A", "d")


Solution

  • By using overloaded implementation of the GroupBy where you can provide the comparer required, e.g. StringComparer.OrdinalIgnoreCase:

      var result = testList
        .GroupBy(item => item, StringComparer.OrdinalIgnoreCase)
        .Where(g => g.Count() > 1)
        .Select(g => g.Key)
        .ToList();