Csharp_dict_ignorecase 参考链接:
今天遇到一个问题,需要在csharp中使用字典,但是字典的key是不区分大小写的,所以需要自己实现一个不区分大小写的字典,好在 csharp 提供这项功能。
核心代码:
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"]);
}
}
输出
1
1