Alex Rivera | Logout

Why use "select new " in LINQ

Asked 2011-09-04T05:48:52.543
17

I am very new to LINQ to SQL, so please forgive me if its a layman sort of question.

I see at many places that we use "select new" keyword in a query. For e.g.

var orders =  from o in db.Orders select new {
                o.OrderID,
                 o.CustomerID,
                 o.EmployeeID,
                 o.ShippedDate
           }

Why don't we just remove select new and just use "select o"

var orders =  from o in db.Orders select o;

What I can differentiate is performance difference in terms of speed, i.e. then second query will take more time in execution than the first one.

Are there any other "differences" or "better to use" concepts between them ?

Edit
Report

1 Answer

2

In the select new, we're creating a new anonymous type with only the properties you need. They'll all get the property names and values from the matching Orders. This is helpful when you don't want to pull back all the properties from the source. Some may be large (think varchar(max), binary, or xml datatypes), and we might want to exclude those from our query.

If you were to select o, then you'd be selecting an Order with all its properties and behaviours.

answered 2011-09-04T05:52:03.340

Your Answer