Get common keys and common values of two dictionaries

ぃ、小莉子 提交于 2020-04-10 08:29:19

问题


Hi I have two dictionaries of next type:

SortedDictionary<string, ClusterPatternCommonMetadata> PatternMetaData { get; set; }

The ClusterPatternCommonMetadata object looks like:

int ChunkQuantity { get; set; }

SortedDictionary<int, int> ChunkOccurrences { get; set; }

First I need the way to find keys of PatternMetaData that is exists in two dictionaries. I find this way:

List<string> commonKeysString=
            vector.PatternMetaData.Keys.Intersect(currentFindingVector.PatternMetaData.Keys)

Then I need to find common values of the founded keys...

Is there is the fast way (lambda, linq, etc) in order to do such operation

Thanks


回答1:


This is called intersection.

You can get the keys using

var data = dictionary1.Keys.Intersect(dictionary2.Keys)

If you want to find equal keys and values that are contained within both dictionaries then just

var equalDictionarys = dictionary1.Intersect(dictionary2);



回答2:


You can also get the whole Dictionary items which have common keys:

var commonDictionaryItems = Dic1.Where(d => Dic2.ContainsKey(d.Key)).ToList();


来源:https://stackoverflow.com/questions/10586736/get-common-keys-and-common-values-of-two-dictionaries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!