Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Dictionary key by using the dictionary value

Tags:

c#

dictionary

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?

like image 975
Rye Avatar asked Oct 23 '10 00:10

Rye


People also ask

Can we get a key from values in dictionary Python?

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.

How do you find the key in a dictionary?

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”.


2 Answers

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).

like image 108
Reed Copsey Avatar answered Sep 21 '22 01:09

Reed Copsey


Brute force.

        int key = dic.Where(kvp => kvp.Value == "a").Select(kvp => kvp.Key).FirstOrDefault(); 
like image 25
John Gardner Avatar answered Sep 18 '22 01:09

John Gardner