C#字典相交

18

我有一个关于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]

My attempt:

resultDict = primaryDict.Keys.Intersect(secondaryDict.Keys).ToDictionary(t => t.Key, t.Value);

这显然行不通,因为primaryDict.Keys.Intersect返回的是键列表...我该如何重新建立一个新字典或缩小原始字典?任何帮助将不胜感激。
4个回答

31
你可以这样操作:
resultDict =  primaryDict.Keys.Intersect(secondaryDict.Keys)
                              .ToDictionary(t => t, t => primaryDict[t]);

或者,另一种选择是:
resultDict =  primaryDict.Where(x => secondaryDict.ContainsKey(x.Key))
                         .ToDictionary(x => x.Key, x => x.Value);

后者可能会稍微更有效,因为它避免了创建一次性集合(由Intersect方法生成的集合),并且不需要第二个按键访问primaryDict。

编辑(根据评论):

resultDict =  
primaryDict.Where(x => secondaryDict.ContainsKey(x.Key))
           .ToDictionary(x => x.Key, x => x.Value + secondaryDict[x.Key]);

2
我认为最新版本更好,因为我认为将字典视为IEnumerable不会发挥字典的优势,并且会以O(n)时间运行。 - Dave Bish
作为后续...在同一表达式中对这些值进行求和是否可能? - Stewart Basterash
@StewartBasterash:将primaryDict中的值与secondaryDict中具有相同键的值进行比较? - digEmAll
明白了...这很有道理...对不起,我很无知...我在.NET中编写Lambda表达式方面是新手,但我真的很喜欢用它来进行数据挖掘... - Stewart Basterash
这比线性更快吗?这有多快? - theonlygusti
显示剩余5条评论

4

你仍然可以在 Linq 语句中使用 primaryDict,因为你创建了一个 新的 字典,并且只有在创建后才将其赋值给变量:

resultDict = primaryDict.Keys
                        .Intersect(secondaryDict.Keys)
                        .ToDictionary(t => t, primaryDict[t]);

2

未测试:

resultDict = primaryDict.Keys.Intersect(secondaryDict.Keys).ToDictionary(t => t.Key, primaryDict[t.Key]);

0
如果你想选择出一个具有两个字典的“value”的对象,因为这可能是你想要的,那么你可以尝试像这样做。假设两个字典的键是相同的,即将它们映射在一起,就像两个系统之间的GUID一样。
dictA.Keys.Intersect(dictB.Keys).Select(x => new MyMappingClass
{
    dictAValue= dictA[x], dictBValue= dictB[x]
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接