HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpCritical

Get dictionary key by value

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
keyvaluegetdictionary

Problem

How do I get a Dictionary key by value in C#?

Dictionary types = new Dictionary()
{
    {"1", "one"},
    {"2", "two"},
    {"3", "three"}
};


I want something like this:

getByValueKey(string value);


getByValueKey("one") must be return "1".

What is the best way do this? Maybe HashTable or SortedLists?

Solution

Values do not necessarily have to be unique, so you have to do a lookup. You can do something like this:

var myKey = types.FirstOrDefault(x => x.Value == "one").Key;


If values are unique and are inserted less frequently than read, then create an inverse dictionary where values are keys and keys are values.

Code Snippets

var myKey = types.FirstOrDefault(x => x.Value == "one").Key;

Context

Stack Overflow Q#2444033, score: 883

Revisions (0)

No revisions yet.