从不区分大小写的列表中获取重复项

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");

此查询区分大小写:

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

它看起来不区分大小写吗? (结果:"A"、"d")

通过替换

.GroupBy(x => x) 

.GroupBy(x => x.ToLower())

您将所有 string 元素变为小写并且不区分大小写。

var result = testList.GroupBy(x => x.ToLower())
                                  .Where(g => g.Count() > 1)
                                  .Select(g => g.Key)
                                  .ToList();

通过使用 GroupBy 重载实现 ,您可以在其中提供所需的比较器,例如StringComparer.OrdinalIgnoreCase:

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