In LINQ, what does the select new keyword combination do?
I haven’t found much documentation on this.
Thanks
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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 newto return new anonymously typed objects:This uses the
newkeyword 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 thenewkeyword just like you’re used to outside of linq:2. Using
select newto construct “regularly” typed objects:This example uses the
newkeyword 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 thenewoperation as the transformation function of theselectstatement. That might make more sense with a counter example to the above two:3. Using
selectwithoutnew, with no transformationOf course you do not need to use
selectandnewtogether. Take this example:This gives you back the original object type that was in the set you were working with – no transformation, and no new object creation.
4. Using
selectwithoutnew, with a transformationAnd finally, a transformation without the
newkeyword:which gives you back some new type of object, generated from the transformation function and not by directly using the
newkeyword to construct it.