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

mjsr picture mjsr · Dec 27, 2010 · Viewed 119.3k times · Source

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.

Answer

Jon Skeet picture Jon Skeet · Dec 27, 2010

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.