c# dictionaries intersect
You could do in this way:
resultDict = primaryDict.Keys.Intersect(secondaryDict.Keys)
.ToDictionary(t => t, t => primaryDict[t]);
or, alternatively:
resultDict = primaryDict.Where(x => secondaryDict.ContainsKey(x.Key))
.ToDictionary(x => x.Key, x => x.Value);
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) :
resultDict =
primaryDict.Where(x => secondaryDict.ContainsKey(x.Key))
.ToDictionary(x => x.Key, x => x.Value + secondaryDict[x.Key]);
You can still use primaryDict
within your Linq statement since you are creating a new dictionary, which only gets assigned to your variable once it is created:
resultDict = primaryDict.Keys
.Intersect(secondaryDict.Keys)
.ToDictionary(t => t, primaryDict[t]);
Untested:
resultDict = primaryDict.Keys.Intersect(secondaryDict.Keys).ToDictionary(t => t.Key, primaryDict[t.Key]);