Csharp_dict_ignorecase 参考链接:
今天遇到一个问题,需要在C#中使用字典,但是字典的key是不区分大小写的,所以需要自己实现一个不区分大小写的字典,好在 c# 提供这项功能。
核心代码:
Dictionary <string, int> dict = new Dictionary <string, int>(StringComparer.OrdinalIgnoreCase);
例子
1using System;
2using System.Collections.Generic;
3public class Program {
4 public static void Main() {
5 Dictionary <string, int> dict = new Dictionary <string, int>(StringComparer.OrdinalIgnoreCase);
6 dict.Add("cricket", 1);
7 dict.Add("football", 2);
8 foreach (var val in dict) {
9 Console.WriteLine(val.ToString());
10 }
11 // case insensitive dictionary i.e. "cricket" is equal to "CRICKET"
12 Console.WriteLine(dict["cricket"]);
13 Console.WriteLine(dict["CRICKET"]);
14 }
15}
输出
1
1