I have two List<T>
of objects with different types (i.e., List<Apple>
and List<Tiger>
). Now I want to combine properties from the 2 objects to generate a new (anonymous) type of objects.
How do I achieve with LINQ?
I have two List<T>
of objects with different types (i.e., List<Apple>
and List<Tiger>
). Now I want to combine properties from the 2 objects to generate a new (anonymous) type of objects.
How do I achieve with LINQ?
So do you just want to combine the first element of the apple list with the first element of the tiger list?
If so, and if you're using .NET 4, you can use Zip
:
var results = apples.Zip(tigers, (apple, tiger) =>
new { apple.Colour, tiger.StripeCount });
If you're not using .NET 4, you could use our implementation of Zip
in MoreLINQ.
If you wanted to match apples with tigers in some other way, you probably want to use a join:
var results = from apple in apples
join tiger in tigers on apple.Name equals tiger.Name
select new { apple.Color, tiger.StripeCount };