大文字小文字を無視するキーコレクション。(HashTable,SortedList,Dictionary,SortedList)

キーと値を持つコレクション。非ジェネリックでは、HashTable,SortedList、ジェネリックではDictionary,SortedListと4種類のコレクションがありますが大文字・小文字を無視する際の記述方法が異なります。非ジェネリックは、使う場面も少なくなって来ていますが.Net Framework 1.0な環境でどうしても。というケースもあると思います。

■HashTable,SortedList(非ジェネリック版)
大文字小文字を無視するHashTable, SortedListを作成するには、それぞれSystem.Collections.Specialized.CollectionsUtil.CreateCaseInsensitiveHashtable,CreateCaseInsensitiveSortedListを使います。


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IgnoreCaseCollection
{
class Program
{
static void Main(string[] args)
{

Hashtable ht = System.Collections.Specialized.CollectionsUtil.CreateCaseInsensitiveHashtable();

ht.Add("HELLO", "TOM");

if( ht.ContainsKey("hello"))
{
Console .WriteLine ("key exist");
}

ht = new Hashtable();

ht.Add("HELLO", "TOM");

if (ht.ContainsKey("hello"))
{
Console.WriteLine("key exist");
}

SortedList st = System.Collections.Specialized.CollectionsUtil.CreateCaseInsensitiveSortedList();

st.Add("HELLO", "TOM");

if (st.ContainsKey("hello"))
{
Console.WriteLine("key exist");
}

st = new SortedList();

st.Add("HELLO", "TOM");

if (st.ContainsKey("hello"))
{
Console.WriteLine("key exist");
}

}
}
}

■Dictionary,SortedList(ジェネリック版)
ジェネリック版では、コンストラクタでStringComparer.CurrentCultureIgnoreCaseを渡すと大文字・小文字を無視するようにできます。比較用のICompareインタフェースを実装したクラスであれば渡すことができるので、大文字・小文字以外(たとえば、平仮名カタカナなどでも)も対応できると思います。


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IgnoreCaseCollection
{
class Program
{
static void Main(string[] args)
{

Dictionary dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase);

dic.Add("HELLO", "TOM");

if (dic.ContainsKey("Hello"))
{
Console.WriteLine("exist key");
}

dic = new Dictionary();

dic.Add("HELLO", "TOM");

if (dic.ContainsKey("Hello"))
{
Console.WriteLine("exist key");
}

SortedList st = new SortedList(StringComparer.CurrentCultureIgnoreCase);

st.Add("HELLO", "TOM");

if (st.ContainsKey("Hello"))
{
Console.WriteLine("exist key");
}

st = new SortedList();

st.Add("HELLO", "TOM");

if (st.ContainsKey("Hello"))
{
Console.WriteLine("exist key");
}

}
}
}