要进行比较,忽略大小写,请使用不区分大小写的Dictionary。
在声明字典时,设置以下属性以获取不区分大小写的字典-
StringComparer.OrdinalIgnoreCase
添加这样的属性-
Dictionary <string, int> dict = new Dictionary <string, int> (StringComparer.OrdinalIgnoreCase);
这是完整的代码-
using System; using System.Collections.Generic; public class Program { public static void Main() { Dictionary <string, int> dict = new Dictionary <string, int> (StringComparer.OrdinalIgnoreCase); dict.Add("cricket", 1); dict.Add("football", 2); foreach (var val in dict) { Console.WriteLine(val.ToString()); } // case insensitive dictionary i.e. "cricket" is equal to "CRICKET" Console.WriteLine(dict["cricket"]); Console.WriteLine(dict["CRICKET"]); } }
输出结果
[cricket, 1] [football, 2] 1 1