I am wondering if there are performance implications of multiple .Where() statements. For example I could write:
var contracts = Context.Contract
.Where(
c1 =>
c1.EmployeeId == employeeId
)
.Where(
c1 =>
!Context.Contract.Any(
c2 =>
c2.EmployeeId == employeeId
&& c1.StoreId == c2.StoreId
&& SqlFunctions.DateDiff("day", c2.TerminationDate.Value, c1.DateOfHire.Value) == 1
)
)
.Where(
c1 =>
!Context.EmployeeTask.Any(
t =>
t.ContractId == c1.Id
)
);
Or alternatively I could combine them all into the one Where() clause, like so:
var contracts = Context.Contract
.Where(
c1 =>
c1.EmployeeId == employeeId
&& !Context.Contract.Any(
c2 =>
c2.EmployeeId == employeeId
&& c1.StoreId == c2.StoreId
&& SqlFunctions.DateDiff("day", c2.TerminationDate.Value, c1.DateOfHire.Value) == 1
)
&& !Context.Employee_Task.Any(
t =>
t.ContractId == c1.Id
)
);
Does the chain of Where() clauses hurt performance or are they equivalent?
In LINQ to Objects, there will be a very small performance hit, because basically the iterator chain will be longer - fetching the next element means going up a long chain of MoveNext() calls.
In LINQ to SQL and similar providers, I'd expect the same SQL to be generated either way, so it wouldn't impact performance there.
EDIT: Since writing this I've found out a bit more about the LINQ to Objects implementation - it's a little more complicated...