Attach two dictionaries using a shared key

I am trying to combine two collections of the Dictionary together based on the overall meaning of the search.

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 above Linq statement is just an example and does not compile. For each entry in idList, pull the value from lookupList based on the corresponding keys.

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

Easiest way to do this with Linq?

+4
source share
4 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} 

An error in your request is one of the areas:

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

a is in the scope on the left. b is in the field of rights.

+14
source

Sorry if I misinterpreted your question, but you just want to get the values ​​from list B only where in list A there is a KeyValuePair with the same key?

 from lookup in lookupList where idList.Keys.Contains(lookup.Key) select lookup.Value; 
+1
source
  var q = from id in idList join entry in lookupList on id.Key equals entry.Key select entry.Value; 

Your desired linq statement would look like this: ID and record should be included provided.

0
source

What do you think about this?

 var values = idList.Keys.Select(i => lookupList[i]); 
0
source

Source: https://habr.com/ru/post/1313026/


All Articles