Create Hashtable from dictionary and specified IEqualityComparer object in CSharp

Description

The following code shows how to create Hashtable from dictionary and specified IEqualityComparer object.

Example


using System;/*from   www .  j  a v  a 2  s . c o  m*/
using System.Collections;
using System.Globalization;

class myCultureComparer : IEqualityComparer
{
    public CaseInsensitiveComparer myComparer;

    public myCultureComparer()
    {
        myComparer = CaseInsensitiveComparer.DefaultInvariant;
    }

    public myCultureComparer(CultureInfo myCulture)
    {
        myComparer = new CaseInsensitiveComparer(myCulture);
    }

    public new bool Equals(object x, object y)
    {
        if (myComparer.Compare(x, y) == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public int GetHashCode(object obj)
    {
        // Compare the hash code for the lowercase versions of the strings. 
        return obj.ToString().ToLower().GetHashCode();
    }
}

public class SamplesHashtable
{
    public static void Main()
    {
        SortedList mySL = new SortedList();
        mySL.Add("FIRST", "Hello");
        mySL.Add("SECOND", "World");
        mySL.Add("THIRD", "!");

        Hashtable myHT2 = new Hashtable(mySL, new myCultureComparer());

        foreach (string firstName in myHT2.Keys)
        {
            Console.WriteLine("{0} {1}", firstName, myHT2[firstName]);
        }        
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Collections »




ArrayList
BitArray
Collection
Comparer
HashSet
Hashtable
LinkedList
List
ListDictionary
OrderedDictionary
Queue
SortedList
SortedSet
Stack
StringCollection
StringDictionary