In LINQ-to-Entities you can query entities by doing:
var students = SchoolContext.Students.Where(s => s.Name == "Foo" && s.Id == 1);
I know that behind the scenes it will be translated to SQL to something similar to:
SELECT *
FROM Students
WHERE Name = 'Foo' AND Id = 1
However is there a difference (with respect to performance) if I write:
var students =
SchoolContext.Students
.Where(s => s.Name == "Foo")
.Where(s => s.Id == 1);
Will it be translated to the same SQL query? From my understanding .Where()
will return IEnumerable<T>
so the second .Where()
will filter the entities in-memory instead of translating the IQueryable<T>
to SQL, is that correct?
Filter collections using Where clause in C#. A single query expression may have multiple where clauses.
LINQ is not faster than For Each - dispelling the myth of avoiding For Each.
In some cases LINQ is just as fast if not faster than other methods, but in other cases it can be slower. We work on a project that we converted to linq and the data lookup is faster but the merging of data between two tables is much slower.
The first .Where()
clause will still return an IQueryable<T>
. As long as you are operating on an IQueryable<T>
it will continue building up the SQL query and execute it when the collection needs to be brought into memory (eg: as @anaximander stated when used in a foreach
loop or ToList()
operation.
Therefore:
SchoolContext.Students.Where(s => s.Name == "Foo").Where(s => s.Id == 1);
Still translates into:
SELECT *
FROM Students
WHERE Name = 'Foo' AND Id = 1
Whilst the below 2 statements will translate into the same query:
SchoolContext.Students.Where(s => s.Name == "Foo").Where(s => s.Id == 1);
SchoolContext.Students.Where(s => s.Name == "Foo" && s.Id == 1);
First Where returns IQueryable<T>
so there will be no performance difference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With