I have 2 dictionaries of type Dictionary<int, (int, int)>
, first int
being their key, (int, int)
being their values.
Using var intersections = dict1.Values.Intersect(dict2.Values);
I can compare values and return an IEnumerable of all values that coincide between the two, however that doesn't give me the keys. And using var intersections = dict1.Keys.Intersect(dict2.Keys);
will return keys appearing in both dictionaries, which is... every single key because the keys just start at 1 and increment by 1 for each entry, so it's useless.
I want to compare the entries by their values, and then have access to their keys. So for example, if the entry (12, 36) is present at Key 20 in dict1
and at Key 45 in dict2
, I'd like to have a way to access 20 and 45.
I'm at a complete loss. I'm able to compare values and return values, I'm able to compare keys and return keys, but I'm unable to compare values and return keys. How do?
Thanks!
You can simply use a Where
filter and check if the other dictionary contains the value:
var matches = dict1.Where(d => dict2.ContainsValue(d.Value));
This will return an enumerable that you can then use ToDictionary()
or ToList()
as needed.
EDIT:
Use this Union
to return both sides of the match:
dict1.Where(d => dict2.ContainsValue(d.Value))
.Union(dict2.Where(d => dict1.ContainsValue(d.Value)));
HTH