How to get the dictionary key by using the dictionary value?
when getting the value using the key its like this:
Dictionary<int, string> dic = new Dictionary<int, string>(); dic.Add(1, "a"); Console.WriteLine(dic[1]); Console.ReadLine();
How to do the opposite?
We can also fetch the key from a value by matching all the values using the dict. item() and then print the corresponding key to the given value.
Using the Inbuilt method get() method returns a list of available keys in the dictionary. With the Inbuilt method keys(), use the if statement to check if the key is present in the dictionary or not. If the key is present it will print “Present” Otherwise it will print “Not Present”.
A dictionary is really intended for one way lookup from Key->Value.
You can do the opposite use LINQ:
var keysWithMatchingValues = dic.Where(p => p.Value == "a").Select(p => p.Key); foreach(var key in keysWithMatchingValues) Console.WriteLine(key);
Realize that there may be multiple keys with the same value, so any proper search will return a collection of keys (which is why the foreach exists above).
Brute force.
int key = dic.Where(kvp => kvp.Value == "a").Select(kvp => kvp.Key).FirstOrDefault();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With