Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get index of a key/value pair in a C# dictionary based on the value

I would like to know if some property or method exists that gets the index of a specific value.

I found that dictionaries have the Contains() method which returns true if the value passed in exists, so this method almost implements what I need.

I know that I can loop through all the value pairs and check the condition, but I ask because maybe there's an optimized way of doing this.

like image 224
mjsr Avatar asked Dec 27 '10 13:12

mjsr


People also ask

How do I find the index of a key in a dictionary?

Use the list[index] function to get index numbers from the dictionary. It will return the key and also use the items() function to return a collection from a dictionary.

Does dictionary have index in C#?

+1 For OrderedDictionary , since Dictionary does not have indices.

How do I find the value of a key?

You can use the get() method of the dictionary ( dict ) to get any default value without an error if the key does not exist. Specify the key as the first argument. The corresponding value is returned if the key exists, and None is returned if the key does not exist.

Can a key-value pair be a list?

A value in the key-value pair can be a number, a string, a list, a tuple, or even another dictionary.


1 Answers

There's no such concept of an "index" within a dictionary - it's fundamentally unordered. Of course when you iterate over it you'll get the items in some order, but that order isn't guaranteed and can change over time (particularly if you add or remove entries).

Obviously you can get the key from a KeyValuePair just by using the Key property, so that will let you use the indexer of the dictionary:

var pair = ...; var value = dictionary[pair.Key]; Assert.AreEqual(value, pair.Value); 

You haven't really said what you're trying to do. If you're trying to find some key which corresponds to a particular value, you could use:

var key = dictionary.Where(pair => pair.Value == desiredValue)                     .Select(pair => pair.Key)                     .FirstOrDefault(); 

key will be null if the entry doesn't exist.

This is assuming that the key type is a reference type... if it's a value type you'll need to do things slightly differently.

Of course, if you really want to look up values by key, you should consider using another dictionary which maps the other way round in addition to your existing dictionary.

like image 87
Jon Skeet Avatar answered Sep 21 '22 05:09

Jon Skeet