Combining two classes into a dictionary using LINQ

I have two classes that have two common attributes: Id and Information.

public class Foo { public Guid Id { get; set; } public string Information { get; set; } ... } public class Bar { public Guid Id { get; set; } public string Information { get; set; } ... } 

Using LINQ, how can I take a populated list of Foo objects and a populated list of Bar objects:

 var list1 = new List<Foo>(); var list2 = new List<Bar>(); 

and combine the identifier and information of each of them into one dictionary:

 var finalList = new Dictionary<Guid, string>(); 

Thanks in advance.

+4
source share
2 answers

It sounds like you could:

 // Project both lists (lazily) to a common anonymous type var anon1 = list1.Select(foo => new { foo.Id, foo.Information }); var anon2 = list2.Select(bar => new { bar.Id, bar.Information }); var map = anon1.Concat(anon2).ToDictionary(x => x.Id, x => x.Information); 

(You can do all this in one statement, but I think it is clearer).

+8
source
  var finalList = list1.ToDictionary(x => x.Id, y => y.Information) .Union(list2.ToDictionary(x => x.Id, y => y.Information)) .ToDictionary(x => x.Key, y => y.Value); 

Make sure the identifier is unique. If not, they will be overwritten by the first dictionary.

EDIT: added. ToDictionary (x => x.Key, y => y.Value);

0
source

All Articles