dev hedgehog
dev hedgehog

Reputation: 8791

Create a dictionary by filtering two lists with LINQ

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

Answers (3)

Nikola.Lukovic
Nikola.Lukovic

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

Richard
Richard

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

ASh
ASh

Reputation: 35646

Join lists and put result into a dictionary

var d = list1.Join(list2, i=>i, o=>o.Id, (i,o)=>o)
             .ToDictionary(o=>o.Id);

try if with a fiddle

Upvotes: 6

Related Questions