Selecting the first item from a query eficiently

Viewed 50

Been reading Microsoft's LINQ docs for a while in search for the correct way to do this. Microsoft's example is the following:

Customer custQuery =
    (from custs in db.Customers
    where custs.CustomerID == "BONAP"
    select custs)
    .First();

This obviosly works and it's the obvious way to do it(except for using FirstOrDefault() rather than First()), however to me, it looks like this runs the query and after it's done it selects the first.

Is there a way to return the first result and not continue the query?

1 Answers

however to me, it looks like this runs the query and after it's done it selects the first

Nope. The query inside the parentheses returns an IQueryable object, which is basically the representation of a query that hasn't been run yet. It's only when you call .First() does it actually process the IQueryable object and translate it into a database query, and without looking I guarantee you it only asks the database for the first item.

However, if you were to write .ToList().First() instead of just .First() (and you see beginners making this mistake in less obvious ways), it would indeed load everything into memory and then pull the first object from it.

But the code you've pasted is perfectly efficient.

Related