Pollitzer
Pollitzer

Reputation: 1620

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

Upvotes: 3

Views: 3584

Answers (3)

Dmitrii Bychenko
Dmitrii Bychenko

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

Sajeetharan
Sajeetharan

Reputation: 222582

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

Upvotes: 1

fubo
fubo

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

Related Questions