LINQ不同的运算符,忽略大小写?

给出以下简单的例子:

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

看来CaseInsensitiveComparer实际上并没有被用来做大小写不敏感的比较。

换句话说, distinctList包含与列表相同数量的项目。 相反,我认为,例如,“三”和“三”被认为是平等的。

我是否错过了一些东西,或者这是一个Distinct运算符的问题?

StringComparer做你所需要的:

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

(或不变的/序号/等等,这取决于你所比较的数据)

[如果你想要最简洁的方法,请参阅Marc Gravells的答案]

经过布拉德利·格兰杰的一些调查和良好的反馈,我实现了以下的IEqualityComparer。 它支持不区分大小写的Distinct()语句(只需将这个实例传递给Distinct运算符):

 class IgnoreCaseComparer : IEqualityComparer<string> { public CaseInsensitiveComparer myComparer; public IgnoreCaseComparer() { myComparer = CaseInsensitiveComparer.DefaultInvariant; } public IgnoreCaseComparer(CultureInfo myCulture) { myComparer = new CaseInsensitiveComparer(myCulture); } #region IEqualityComparer<string> Members public bool Equals(string x, string y) { if (myComparer.Compare(x, y) == 0) { return true; } else { return false; } } public int GetHashCode(string obj) { return obj.ToLower().GetHashCode(); } #endregion } 

这是一个更简单的版本。

 List<string> list = new List<string>() { "One", "Two", "Three", "three", "Four", "Five" }; var z = (from x in list select new { item = x.ToLower()}).Distinct(); z.Dump(); 

  ## Distinct Operator( Ignoring Case) ## string[] countries = {"USA","usa","INDIA","UK","UK" }; var result = countries.Distinct(StringComparer.OrdinalIgnoreCase); foreach (var v in result) { Console.WriteLine(v); } 

OutPut将会

  USA INDIA UK