tags:

views:

71

answers:

3

Hello!

I have a dictionary with non unique values and I want to count the matches of a string versus the values.

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

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

/Rickard Haake

+4  A: 

To get the count use Values.Count:

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

To get the keys I prefer the query syntax:

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

Note that this will require scanning the entire dictionary. For small dictionaries or infrequent lookups this may not be a problem.

If you are making many lookups you may wish to maintain a second dictionary that maps the values to the keys. Whilst this will speed up lookups, it will slow down modifications as both dictionaries will need updating for each change.

Mark Byers
Thanks, that is a good answer.
Rickard Haake
+8  A: 

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

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

To find the keys that have this value you could do this:

dict.Where(kv => kv.Value == a).Select(kv => kv.Key);
Simon Steele
Thanks, that is perfect
Rickard Haake
+1  A: 

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

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