Posted by: Cirilo Meggiolaro | 03/13/2009

Tip of the day #150 – Creating case insensitive hashtables and sorted lists

The CollectionsUtil class available under the System.Collections.Specialized namespace provides some static methods to create instances of hashtables and sorted lists that are case insensitive.

Method overloads

The following method overloads are available for both hashtables and sorted lists:

public static Hashtable CreateCaseInsensitiveHashtable();
public static Hashtable CreateCaseInsensitiveHashtable(IDictionary d);
public static Hashtable CreateCaseInsensitiveHashtable(int capacity);
public static SortedList CreateCaseInsensitiveSortedList();

How to…

Hashtable ht = CollectionsUtil.CreateCaseInsensitiveHashtable();
ht.Add(“MyKey”, “originalValue”);
ht.Add(“mykey”, “modifiedValue”);
Console.WriteLine(ht[“MyKey”].ToString());

The code above raises an exception in runtime because the hashtable is case insensitive and both MyKey and mykey are considered the same key now.

The following code shows the same hashtable and the value being modified by a key with different case.

Hashtable ht = CollectionsUtil.CreateCaseInsensitiveHashtable();
ht.Add(“MyKey”, “originalValue”);
ht[“mykey”] = “modifiedValue”;
Console.WriteLine(ht[“MyKey”].ToString());

Output: modifiedValue


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: