Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use LINQ to generate new type of objects

Tags:

c#

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?

like image 216
Ricky Avatar asked Sep 24 '10 06:09

Ricky


People also ask

Does LINQ create new object?

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.

Which keyword is used to create new types LINQ?

Data Transformations with LINQ (C#) You can modify the sequence by sorting and grouping and create new types by using the select clause.

What type of objects can query using LINQ?

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.


1 Answers

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 };
like image 118
Jon Skeet Avatar answered Oct 30 '22 12:10

Jon Skeet