Occurance of Values in a Dictionary C#
c#, linq
Solution
If you mean only the values that occur more than once, you can do group the key/value pairs by value, filter out the groups with only one item and select the common group key (original value that appears multiple times) from what remains:
var multiples = dictionary.GroupBy(p => p.Value)
.Where(g => g.Count() > 1)
.Select(g => g.Key);
If you want all pairs of keys/values where the values occur more than once, this variation will do it:
var multiples = dictionary.GroupBy(p => p.Value)
.Where(g => g.Count() > 1)
.SelectMany(g => g);
The only difference is in the last step, where after casting out groups with just one value the contents of all remaining groups are "unwrapped" into a single sequence of key/value pairs.
In the latter case, you can turn the results back into a dictionary (essentially filtering out values that appear only once) by following up with
.ToDictionary(p => p.Key, p => p.Value)
The last example, in query form:
var multiples = from pair in dictionary
group pair by pair.Value into grp
where grp.Count() > 1
from pair in grp select pair;
Problem
Is there a way that I have a dictionary and I need to get only the pair that occurs more than once in Linq ? for example in ``` {1, "entries"}, {2, "images"}, {3, "views"}, {4, "images"}, {5, "results"}, {6, "images"}, {7, "entries"} ``` I get ``` {1, "entries"}, {2, "images"}, {6, "images"}, {7, "entries"} ```