views:

87

answers:

4

Hi all,

I have a silly question. I would like to know if there is performance deference in these two quries:

var cObject = from cust in entities.Customer 
          where cust.id == cid
      select cust;

and

var cObject = entities.Customer.First( c=> c.id == cid);

My query return only one record as I am querying with the primary key. But do they make any difference?

+3  A: 

Performance wise, they should be similar.

Type wise they are different though. The first returns an IEnumerable IQueryable object with a single element. The second actually returns a Customer object.

Justin Niessner
The first line returns an `IQueryable`, strictly speaking. But this is generally correct if one presumes that eventually someone will actually look into the queryable.
Craig Stuntz
A: 

There is no performance.

First Microsoft introduce

var cObject = entities.Customer.First( c=> c.id == cid);

Edit: Returns IQueryable

Then they added sugar to it , to make work easy is

var cObject = from cust in entities.Customer 
          where cust.id == cid
      select cust;

Edit Returns customer object

anishmarokey
That's what I thought too, but see Justin's answer posted here
Robert Harvey
i was knowing that,When i was planed to edit power has gone .. So..Any way thanks
anishmarokey
+1  A: 

If your LINQ provider supports the notion of a "single record query", then a query using First would probably be slightly faster.

Note that you could use the first one and then do cObject.First() to get the same effect.

Stephen Cleary
+1  A: 

As Craig Stuntz points out in the comments on the question, you have to be careful about profiling Linq code, since lazy loading delayed execution can skew your profiling results.

To get a clear reading, you would have to call ToList() to force the query to fully execute, and then you would have to do the same on your second example to make it apples to apples.

In any case, were the second query rewritten to return an IEnumerable IQueryable with one customer object instead of a single customer object, the two statements would be functionally identical.

Robert Harvey