1: The most straightforward method of looping can be divided into traversing key-value pairs and all keys.
2: query using the LINQ method (of course, the corresponding namespace using system. LINQ should be added here)
The following is a simple code example:
private void GetDicKeyByValue(){ Dictionary<string, string> dic = new Dictionary<string, string>(); dic.Add("1", "1"); dic.Add("2", "2"); dic.Add("3", "2"); //foreach KeyValuePair traversing foreach (KeyValuePair<string, string> kvp in dic) { if (kvp.Value.Equals("2")) { //...... kvp.Key; } } //foreach dic.Keys foreach (string key in dic.Keys) { if (dic[key].Equals("2")) { //...... key } } //Linq var keys = dic.Where(q => q.Value == "2").Select(q => q.Key); //get all keys List<string> keyList = (from q in dic where q.Value == "2" select q.Key).ToList<string>(); //get all keys var firstKey = dic.FirstOrDefault(q => q.Value == "2").Key; //get first key}
.....
C # dictionary get the corresponding key value through value