本文介绍了C#字典相交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于LINQ的/λ问题了以下问题:

I have a question about Linq / Lambda and the following issue:

我两本字典,小学和中学......这些两个字典定义为关键=字符串值= INT。我需要如果密钥二次词典交叉修剪下来的主字典

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.

如:

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]

我的尝试:

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

这是因为primaryDict.Keys.Intersect是返回键的列表,显然是行不通的...我将如何重新建立一个新的字典,或配对关闭主字典? 。任何帮助,将不胜感激。

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.

推荐答案

您可以这样做:

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);



后者可能会更有效,因为避免了扔掉的集合的创建(生成一个由相交法)和不需要第二接入逐键 primaryDict

修改(按评论):

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

这篇关于C#字典相交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 09:52