Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all keys in Dictionary containing value x

I have this:

Dictionary<integer, string> dict = new Dictionary<integer, string>();

I want to select all the items in the dictionary that contain the value abc.

Is there an inbuilt function that lets me do this easily?

like image 610
Elmo Avatar asked Jan 03 '13 19:01

Elmo


People also ask

How do I get all the keys and values in a dictionary?

In Python to get all key-values pair from the dictionary, we can easily use the method dict. items(). This method helps the user to extract all keys and values from the dictionary and iterate the object with a for loop method.

How do you get the list of all the keys in a dictionary?

Use the keys() function() and apply it to the input dictionary to get the list of all the keys of a dictionary. Print the list of keys of a dictionary by traversing through each key in the above keys list using the list comprehension and for loop.

How do you get all values from a Python dictionary?

We can use the values() method in Python to retrieve all values from a dictionary. Python's built-in values() method returns a view object that represents a list of dictionaries containing every value. This article explains about the various ways to print all the values of a dictionary in Python.


1 Answers

Well it's reasonably simple with LINQ:

var matches = dict.Where(pair => pair.Value == "abc")
                  .Select(pair => pair.Key);

Note that this won't be even slightly efficient - it's an O(N) operation, as it needs to check every entry.

If you need to do this frequently, you may want to consider using another data structure - Dictionary<,> is specifically designed for fast lookups by key.

like image 106
Jon Skeet Avatar answered Sep 18 '22 18:09

Jon Skeet