Ste*_*ash 14 c# dictionary key intersect
我有关于Linq/Lambda的问题以及以下问题:
我有两个词典,主要和次要......这两个词典被定义为Key = string,Value = int.如果KEYS与辅助字典相交,我需要修剪主字典.
即:
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]
Run Code Online (Sandbox Code Playgroud)
我的尝试:
resultDict = primaryDict.Keys.Intersect(secondaryDict.Keys).ToDictionary(t => t.Key, t.Value);
Run Code Online (Sandbox Code Playgroud)
这显然不起作用,因为primaryDict.Keys.Intersect返回一个键列表...我将如何重新建立一个新词典,或者配对主词典?任何帮助,将不胜感激.
dig*_*All 22
你可以这样做:
resultDict = primaryDict.Keys.Intersect(secondaryDict.Keys)
.ToDictionary(t => t, t => primaryDict[t]);
Run Code Online (Sandbox Code Playgroud)
或者,或者:
resultDict = primaryDict.Where(x => secondaryDict.ContainsKey(x.Key))
.ToDictionary(x => x.Key, x => x.Value);
Run Code Online (Sandbox Code Playgroud)
后者可能稍微更高效,因为避免创建一个抛弃集合(由Intersect方法生成的集合),并且不需要第二次按键访问primaryDict.
编辑(根据评论):
resultDict =
primaryDict.Where(x => secondaryDict.ContainsKey(x.Key))
.ToDictionary(x => x.Key, x => x.Value + secondaryDict[x.Key]);
Run Code Online (Sandbox Code Playgroud)