Saurabh Sahasrabuddhe
Saurabh Sahasrabuddhe

Reputation: 23

compare two dictionaries by key to obtain values of matching keys

I have two dictionaries A and B.

A - (a,b) (c,d) (e,f)
B - (a,p) (c,q) (g,h)

I want to be able to make a new dictionary C which will be as below -

C - (b,p) (d,q)

Is there any way I can do this?

This is what I currently have:

var C= B.Where(d => A.ContainsKey(d.Key)).ToList();

Upvotes: 1

Views: 1437

Answers (1)

Thomas Levesque
Thomas Levesque

Reputation: 292765

Easy with Linq ;)

var query =
    from x in dictionary1
    join y in dictionary2 on x.Key equals y.Key
    select new { Value1 = x.Value, Value2 = y.Value };

var newDict = query.ToDictionary(item => item.Value1, item => item.Value2);

However it's not the most efficient approach, since it doesn't take advantage of the dictionary's fast lookup. A faster approach would be something like this:

var newDict = new Dictionary<string, string>(); // adjust the key and value types as needed
foreach (var kvp in dictionary1)
{
    string value2;
    if (dictionary2.TryGetValue(kvp.Key, out value2))
    {
        newDict.Add(kvp.Value, value2);
    }
}

Upvotes: 4

Related Questions