Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Distinct operator, ignore case?

Given the following simple example:

    List<string> list = new List<string>() { "One", "Two", "Three", "three", "Four", "Five" };      CaseInsensitiveComparer ignoreCaseComparer = new CaseInsensitiveComparer();      var distinctList = list.Distinct(ignoreCaseComparer as IEqualityComparer<string>).ToList(); 

It appears the CaseInsensitiveComparer is not actually being used to do a case-insensitive comparison.

In other words distinctList contains the same number of items as list. Instead I would expect, for example, "Three" and "three" be considered equal.

Am I missing something or is this an issue with the Distinct operator?

like image 928
Ash Avatar asked Nov 12 '08 04:11

Ash


1 Answers

StringComparer does what you need:

List<string> list = new List<string>() {     "One", "Two", "Three", "three", "Four", "Five" };  var distinctList = list.Distinct(     StringComparer.CurrentCultureIgnoreCase).ToList(); 

(or invariant / ordinal / etc depending on the data you are comparing)

like image 196
Marc Gravell Avatar answered Oct 22 '22 21:10

Marc Gravell