I have a question about Linq / Lambda and the following issue:
I have two dictionaries, primary and secondary… These two dictionaries are defined as Key=string, Value=int. I need to trim down the primary dictionary if the KEYS intersect with secondary dictionary.
i.e.:
primaryDict = ["thing1", 33] ["thing2", 24] ["thing3", 21] ["thing4", 17] ["thing5", 12]
secondaryDict = ["thing1", 22] ["thing3", 20] ["thing4", 19] ["thing7", 17] ["thing9", 10]
resultDict = ["thing1", 33] ["thing3", 21] ["thing4", 17]
My attempt:
resultDict = primaryDict.Keys.Intersect(secondaryDict.Keys).ToDictionary(t => t.Key, t.Value);
This obviously does not work because the primaryDict.Keys.Intersect is returning a list of keys… how would I reestablish a new dictionary, or pair down the primary dictionary? Any help would be appreciated.
You could do in this way:
or, alternatively:
the latter maybe is slightly more efficient because avoids the creation of a throw-away collection (the one generated by the Intersect method) and does not require a second access-by-key to
primaryDict.EDIT (as per comment) :