Get all keys in Dictionary containing value x
31,986
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.
Related videos on Youtube
Author by
Elmo
Updated on July 09, 2022Comments
-
Elmo almost 2 years
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?
-
jmrnet over 11 yearsYou could if you want to get the keys that have a value that contains "abc" you could also: var matches = dict.Where(pair => pair.Value.Contains("abc")) .Select(pair => pair.Key);
-
Jon Skeet over 11 years@User:
Dictionary<,>
is just shorthand forDictionary<TKey, TValue>
. How big is your dictionary? How many values do you need to search for? Once per second isn't very often, if it's a reasonably small dictionary and you're only looking for a single value... -
Elmo over 11 yearsThe dictionary's capacity is 10 keys and 4 values ("Left","Right","Front","Back"). And sometimes the function runs about 10 times per second.
-
Casperah over 11 yearsFor such a small collection you shouldn't worry, However, if you don't use the special indexing feature of Dictionary you might be better off with a List<Tuple<int, string>>.
-
stephanmg over 4 years@JonSkeet: Which data structure would you recommend then?
-
Jon Skeet over 4 years@stephanmg: I'd need to know more about the precise requirements. If you have such requirements, I suggest you ask about that in a new question, with details.
-
stephanmg over 4 years@JonSkeet: You are right. I'd assume the OP wanted a "bidirectionally" fast access. In this case one could use a second dictionary in which key/val pairs are inverted.