Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging two classes into a Dictionary using LINQ

I have two classes which share 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 merge the Id and Information of each into a single dictionary:

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

Thank you in advance.

like image 257
Jonathan Avatar asked Feb 20 '23 17:02

Jonathan


1 Answers

Sounds like you could do:

// 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 could do all of this in one statement, but I think it's clearer this way.)

like image 176
Jon Skeet Avatar answered Feb 22 '23 08:02

Jon Skeet