標籤:
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 KeyValuePair10 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.Keys20 list.Clear();21 foreach (int key in dict.Keys)22 {23 if (dict[key].Equals("2"))24 {25 list.Add(key); // key26 }27 }28 29 // Linq30 List<int> keyList = dict.Where(q => q.Value == "2")31 .Select(q => q.Key).ToList<int>(); //get all keys32 33 keyList = (from q in dict34 where q.Value == "2"35 select q.Key).ToList<int>(); //get all keys36 37 var firstKey = dict.FirstOrDefault(q => q.Value == "2").Key; //get first key38 }
C# Dictionary已知value擷取對應的key