[C#.NET][VB.NET] 實作 IEqualityComparer 不分大小寫

  • 10287
  • 0
  • C#
  • 2009-06-11

[C#.NET][VB.NET] 實作 IEqualityComparer 不分大小寫

實作IEqualityComparer,不分大小寫比較

 

 

 

       //實作
        public class InComparer : IEqualityComparer
        {
            CaseInsensitiveComparer myComparer = new CaseInsensitiveComparer();
            public int GetHashCode(object obj)
            {
                return obj.ToString().ToLowerInvariant().GetHashCode();
            }
            public new bool Equals(object x, object y)
            {
                if (myComparer.Compare(x, y) == 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

 

 

 

 

因為不分大小寫所以First與first視為相同,程式在執行時會出現例外。

//引用類別
Hashtable myData = new Hashtable(new InComparer());
myData.Add("First", "1st");
myData.Add("Senond", "2nd");
myData.Add("Third", "3rd");
myData.Add("Fourth", "4th");
myData.Add("Fifth", "5th");
myData.Add("first", "1st");
foreach (DictionaryEntry myEntry in myData)
{
       Console.WriteLine("{0} = {1}", myEntry.Key, myEntry.Value);
}

 

 

當然也可以用CollectionsUtil類別來不分大小寫,這段程式看起來就短多了。

Hashtable myColl = CollectionsUtil.CreateCaseInsensitiveHashtable();
myColl.Add("A", "1234");
myColl.Add("a", "1234");

 

 

 

若有謬誤,煩請告知,新手發帖請多包涵


Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET

Image result for microsoft+mvp+logo