Reputation: 11
I'm new to EF/Linq-To-SQL. I read on SO previously that IQueryable is beneficial over IEnumerable in that it does lazy evaluation. Concerning the following simple example:
var records = db.Employees.Where(x => x.EmployeeID == "3" );
if (records.Any())
{
var topRecord = records.First();
}
Is the IQueryable expression being evaluated twice? Once to check for any elements in the result set, and once when retrieving the first element? If so, is there a more efficient way to peform such a select?
Upvotes: 1
Views: 1232
Reputation: 269368
Yes, in this case the query will be executed twice: firstly for Any
and then for First
.
You could probably use FirstOrDefault
instead:
var topRecord = db.Employees.FirstOrDefault(x => x.EmployeeID == "3" );
// topRecord will be null if there's no match
if (topRecord != null)
{
...
}
Upvotes: 4