patterncsharpCritical
Get dictionary key by value
Viewed 0 times
keyvaluegetdictionary
Problem
How do I get a Dictionary key by value in C#?
I want something like this:
What is the best way do this? Maybe HashTable or SortedLists?
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:
If values are unique and are inserted less frequently than read, then create an inverse dictionary where values are keys and keys are values.
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.