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?
The type of sequence returned by a query is determined by the type of value returned by the select clause. LINQ select can return a sequence that contains elements created during the execution of the query.
Data Transformations with LINQ (C#) You can modify the sequence by sorting and grouping and create new types by using the select clause.
You can use LINQ to query any enumerable collections such as List<T>, Array, or Dictionary<TKey,TValue>. The collection may be user-defined or may be returned by a . NET API.
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 };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With