Reputation: 1620
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")
Upvotes: 3
Views: 3584
Reputation: 186678
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();
Upvotes: 14
Reputation: 222582
var result = testList.GroupBy(x => x.ToLower())
.Where(g => g.Count() > 1)
.Select(g => g.Key)
.ToList();
Upvotes: 1
Reputation: 45947
By replacing
.GroupBy(x => x)
with
.GroupBy(x => x.ToLower())
you turn all string
elements to lower case and group case insensitive.
Upvotes: 3