C# Dictionary已知value获取对应的key
1:循环遍历法,分为遍历key-value键值对和遍历所有key两种形式
2:使用Linq查询法
1 private void GetDictKeyByValue()
2 {
3 Dictionary<int, string> dict = new Dictionary<int, string>();
4 dict.Add(1, "1");
5 dict.Add(2, "2");
6 dict.Add(3, "2");
7 dict.Add(4, "4");
8
9 // foreach KeyValuePair
10 List<int> list = new List<int>();
11 foreach (KeyValuePair<int, string> kvp in dict)
12 {
13 if (kvp.Value.Equals("2"))
14 {
15 list.Add(kvp.Key); // kvp.Key;
16 }
17 }
18
19 // foreach dic.Keys
20 list.Clear();
21 foreach (int key in dict.Keys)
22 {
23 if (dict[key].Equals("2"))
24 {
25 list.Add(key); // key
26 }
27 }
28
29 // Linq
30 List<int> keyList = dict.Where(q => q.Value == "2")
31 .Select(q => q.Key).ToList<int>(); //get all keys
32
33 keyList = (from q in dict
34 where q.Value == "2"
35 select q.Key).ToList<int>(); //get all keys
36
37 var firstKey = dict.FirstOrDefault(q => q.Value == "2").Key; //get first key
38 }