Why is it common to use select new in linq?

Viewed 47

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;

1 Answers

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 } ;
Related