110

给出以下简单示例:

    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包含与list 相同数量的项目。相反,我希望,例如,“三”和“三”被认为是相等的。

我是否遗漏了什么,或者这是 Distinct 运算符的问题?

4

4 回答 4

262

StringComparer做你需要的:

List<string> list = new List<string>() {
    "One", "Two", "Three", "three", "Four", "Five" };

var distinctList = list.Distinct(
    StringComparer.CurrentCultureIgnoreCase).ToList();

(或不变/有序/等,具体取决于您要比较的数据)

于 2008-11-12T06:41:52.843 回答
5

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

经过 Bradley Grainger 的一些调查和良好反馈后,我实施了以下 IEqualityComparer。它支持不区分大小写的 Distinct() 语句(只需将 this 的一个实例传递给 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
}
于 2008-11-12T06:42:22.640 回答
1

 ## 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);
  }

输出将是

   USA 
   INDIA
   UK
于 2017-04-28T11:11:00.210 回答
0

这是一个更简单的版本。

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();
于 2009-01-13T18:02:18.247 回答