9

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

2 Answers 2

15

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);
4
  • So there is no way to get intersected Dictionary<K,V> by keys and values from two given dictionaries?
    – AlexBerd
    May 14, 2012 at 15:56
  • @AlexanderBerdichevsky Just to clarify.. You want to get all the dictionarys where both key and value match?
    – AlanFoster
    May 14, 2012 at 15:57
  • I want to create one dictionary from two that inside of it would the common keys and common values of keys
    – AlexBerd
    May 14, 2012 at 16:01
  • 1
    Yes, this is called intersection :) Try the suggestion in my answer please
    – AlanFoster
    May 14, 2012 at 16:04
6

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.