find the key associated with a value in a map in csharp

To find the key associated with a specific value in a Dictionary (which is the C# equivalent of a map), you can use LINQ to search for the first key that has the desired value:

main.cs
using System.Linq;

// declare and populate a dictionary of key-value pairs
Dictionary<string, int> myDict = new Dictionary<string, int>();
myDict.Add("apple", 1);
myDict.Add("orange", 2);
myDict.Add("banana", 3);

// search for the key associated with the value 2
string key = myDict.FirstOrDefault(x => x.Value == 2).Key;

Console.WriteLine(key); // output: "orange"
369 chars
13 lines

In the above example, the FirstOrDefault method of the Dictionary is used with a lambda expression to search for the first key-value pair where the value is equal to 2. The Key property of that pair is then returned. If no matching key is found, null is returned.

related categories

gistlibby LogSnag