1 private void GetDicKeyByValue()
2 {
3 Dictionary<string, string> dic = new Dictionary<string, string>();
4 dic.Add("1", "1");
5 dic.Add("2", "2");
6 dic.Add("3", "2");
7 //foreach KeyValuePair traversing
8 foreach (KeyValuePair<string, string> kvp in dic)
9 {
10 if (kvp.Value.Equals("2"))
11 {
12 //...... kvp.Key;
13 }
14 }
15
16 //foreach dic.Keys
17 foreach (string key in dic.Keys)
18 {
19 if (dic[key].Equals("2"))
20 {
21 //...... key
22 }
23 }
24
25 //Linq
26 var keys = dic.Where(q => q.Value == "2").Select(q => q.Key); //get all keys
27
28 List<string> keyList = (from q in dic
29 where q.Value == "2"
30 select q.Key).ToList<string>(); //get all keys
31
32 var firstKey = dic.FirstOrDefault(q => q.Value == "2").Key; //get first key
33 }