When is it required to use new in the select clause as in the following example? Thanks.
var results = from person in people
select new { FN = person.FirstName, LN = person.LastName };
I’ve searched and partially understand this: “In the select new, we’re creating a new anonymous type with only the properties you need.” But does it mean I can omit new and not get an anonymous type?
To restate my question in another way: is ‘new’ optional? Is ‘new’ here similar to C# new where it is not required with value type?
Can I do this?
var results = from person in people
select { FN = person.FirstName, LN = person.LastName };
No,
newis not optional if you’re selecting “new” objects. (which is what you are doing. You are creating new objects of an anonymous type with 2 propertiesFNandLN)Simply omitting
newis a syntax error.If you have an existing type you would like to use, (say you’ve defined a
classPersonwith 2 propertiesFNandLN) then you can use that type. E.g.(assuming Person has a parameterless constructor and
FNandLNare properties with setters)The only time you can omit
newis if you are not creating a new object, for instance:There you are selecting just the
LastNameand the result is anIEnumerable<string>