Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join two dictionaries using a common key

Tags:

c#

linq

I am trying to join two Dictionary collections together based on a common lookup value.

var idList = new Dictionary<int, int>();
idList.Add(1, 1);
idList.Add(3, 3);
idList.Add(5, 5);

var lookupList = new Dictionary<int, int>();
lookupList.Add(1, 1000);
lookupList.Add(2, 1001);
lookupList.Add(3, 1002);
lookupList.Add(4, 1003);
lookupList.Add(5, 1004);
lookupList.Add(6, 1005);
lookupList.Add(7, 1006);

// Something like this:
var q = from id in idList.Keys
        join entry in lookupList on entry.Key equals id
        select entry.Value;

The Linq statement above is only an example and does not compile. For each entry in the idList, pull the value from the lookupList based on matching Keys.

The result should be a list of Values from lookupList (1000, 1002, 1004).

What’s the easiest way to do this using Linq?

like image 552
rboarman Avatar asked Jun 16 '10 21:06

rboarman


People also ask

How do I merge dictionaries with common keys?

Merging two dictionaries having common keys using **kwargs Keys that are common in both d1 and d2 will contain values from d2. If d3={**d2,**d1} -Keys that are common in both d1 and d2 will contain values from d1.

How do I merge multiple dictionaries values having the same key in Python?

Python 3.9 has introduced the merge operator (|) in the dict class. Using the merge operator, we can combine dictionaries in a single line of code. We can also merge the dictionaries in-place by using the update operator (|=).

Can we merge two dictionaries?

In the latest update of python now we can use “|” operator to merge two dictionaries. It is a very convenient method to merge dictionaries. Example: Python3.


2 Answers

from id in idList.Keys
where lookupList.ContainsKey(id)
let value1 = idList[id]
let value2 = lookupList[id]
select new {id, value1, value2}

Or, more classically

from kvp1 in idList
join kvp2 in lookupList on kvp1.Key equals kvp2.Key
select new {key = kvp1.Key, value1 = kvp1.Value, value2 = kvp2.Value}

The mistake in your query is one of scoping:

from a in theAs
join b in theBs on (leftside) equals (rightside)

a is in scope in the leftside area. b is in scope in the rightside area.

like image 56
Amy B Avatar answered Nov 02 '22 20:11

Amy B


I apologize if I misinterpretted your question, but do you just want to retrieve the Values from list B only where list A has a KeyValuePair with the same Key?

from lookup in lookupList
where idList.Keys.Contains(lookup.Key)
select lookup.Value;
like image 20
Nathan Taylor Avatar answered Nov 02 '22 20:11

Nathan Taylor