Dictionary<string, T>では、コンストラクタでキーの比較を行うためのIEqualityComparer<string>を指定することが出来るため、StringComparerを指定することでキーの大文字小文字を無視するディクショナリを作成することも出来ます。
StringComparerを指定してキーの大文字と小文字の違いを無視する・無視しないDictionaryを作成する
using System;
using System.Collections.Generic;
class Sample {
static void Main()
{
var dict1 = new Dictionary<string, string>(StringComparer.InvariantCulture); // キーの大文字小文字を無視しない
var dict2 = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase); // キーの大文字小文字を無視する
dict1["foo"] = "bar";
dict1["Foo"] = "Bar";
dict1["FOO"] = "BAR";
dict2["foo"] = "bar";
dict2["Foo"] = "Bar";
dict2["FOO"] = "BAR";
Console.WriteLine("dict1");
foreach (var p in dict1) {
Console.WriteLine("{0} = {1}", p.Key, p.Value);
}
Console.WriteLine("dict2");
foreach (var p in dict2) {
Console.WriteLine("{0} = {1}", p.Key, p.Value);
}
}
}
実行結果
dict1 foo = bar Foo = Bar FOO = BAR dict2 foo = BAR