Reputation: 8791
I need a way to create a Dictionary<key, value>
by filtering data from two lists using a linq statement. For example:
list1: { 1, 2, 3 }
list2: { <apple, 1>, <peach, 3> }
final dictionary should look like this: { <1, <apple, 1>>, <3, <peach, 3>> }
2
in list1 shall be skipped
Please any ideas how to solve this issue by using linq?
Upvotes: 2
Views: 295
Reputation: 1325
You can use SelectMany
if you want:
var result = (from l1 in list1
from l2 in list2
where l1 == l2.Id
select new
{
Id = l1,
Name = l2.Name
}).ToDictionary(k=>k.Id, v=>v.Name);
Upvotes: 2
Reputation: 108975
You can use Enumerable.Zip
to merge two lists into one, and then Enumerable.ToDictionary
to generate the dictionary.
Something like:
var result = list1.Zip(list2, (l, r) => Tuple.Create(l, r))
.ToDictionary(v => v.Item1, v => v.Item2);
Upvotes: 0