Returns the number of matches from a C # dictionary

I have a dictionary with unique values, and I want to count string matches compared to values.

Basically, I am now doing dict.ContainsValue (a) to get bool, telling me if the string a exists in the dict, but I want to know not only if it exists, but how many times it exists (and maybee even get the list from the keys to which it exists)

Is there a way to do this with a dictionary, or should I look for another collection?

/ Rickard Haack

+5
source share
3 answers

To get the number of value instances, you can do something like this:

dict.Values.Count(v => v == a);

To find the keys that have this value, you can do this:

dict.Where(kv => kv.Value == a).Select(kv => kv.Key);
+9

count, .Count:

int count = dict.Values.Count(x => x == "foo");

, :

var keys = from kvp in dict
           where kvp.Value == "foo"
           select kvp.Key;

, . .

, , . , , .

+4

how about using LINQ: if a is the value you're looking for, the code could be

dict.Values.Where(v => v == a).Count();
+1
source

All Articles