独立操作员,忽略大小写?

举个简单的例子:

    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.

换句话说,清单包含与 名单相同数量的项目。相反,我期望,例如,“三”和“三”被认为是相等的。

我是不是漏了什么,还是因为独立接线员的问题?

46873 次浏览

StringComparer做你需要做的:

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


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

(或不变量/序数/等,取决于您比较的数据)

[参见 Marc Gravells 的回答,如果你想要最简洁的方法]

经过一些调查和 Bradley Grainger 的良好反馈,我已经实现了下面的 IEqualityComparer。它支持不区分大小写的 District ()语句(只需将这个语句的一个实例传递给 District 操作符) :

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

输出将是

   USA
INDIA
UK