[SOLVED] Why is it common to use select new in linq?

Issue

This Content is from Stack Overflow. Question asked by userSteve

When I look for examples of LINQ statements, often the select result doesn’t just return the object or properties directly but as a new anonymous type.
Why is this?

eg

var teenStudents = from s in studentList
where s.age > 12 && s.age < 20
select new { s };

why not just select s;



Solution

It really depends on the use case.

If the entire entity data is required, no further projection is required.

var teenStudents = from s in studentList
where s.age > 12 && s.age < 20
select s;

Some scenarios where we project the data into a new anonymous object is

  • When we need to select only specific properties from say a large entity having 20 columns. It makes the querying efficient
  • When we do not have an entity object to project the output to and you don’t intend to create one

It could be something like

var teenStudents = from s in studentList
where s.age > 12 && s.age < 20
select new {Name= s.name, Age = s.age } ;

If you have another DTO class which you can project to, you can do

var teenStudents = from s in studentList
where s.age > 12 && s.age < 20
select new StudentDTO {Name= s.name, Age = s.age } ;


This Question was asked in StackOverflow by userSteve and Answered by WisdomSeeker It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?