Alex Rivera | Logout

Select new keyword combination

Asked 2010-02-14T23:12:27.347
12

In LINQ, what does the select new keyword combination do?

I haven't found much documentation on this.

Thanks

Edit
Report

1 Answer

23

By using select new, you can use the data or objects in the set you are working with to create new objects, either typed anonymously or normally.


1. Using select new to return new anonymously typed objects:

var records = from person in people
              select new { person.name, person.id };

This uses the new keyword to create a set of anonymously typed objects. A new object type is simply created by the compiler, with two properties in it. If you look at the object type in the debugger, you'll see that it has a crazy-looking, auto-generated type name. But you can also use the new keyword just like you're used to outside of linq:


2. Using select new to construct "regularly" typed objects:

var records = from person in people
              select new CreditRecord(person.creditLimit, person.name);

This example uses the new keyword just like you're used to - to construct some known type of object via one of its constructors.

Select is called a transformation (or projection) operator. It allows you to put the data in the set that you are working with through a transformation function, to give you a new object on the other side. In the examples above, we're simply "transforming" the person object into some other type by choosing only specific properties of the person object, and doing something with them. So the combination of select new ... is really just specifying the new operation as the transformation function of the select statement. That might make more sense with a counter example to the above two:


3. Using select without new, with no transformation

answered 2010-02-14T23:15:59.000

Your Answer