Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance for using 2 where clauses in LINQ

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?

like image 523
rexcfnghk Avatar asked Oct 15 '13 09:10

rexcfnghk


People also ask

Can we use multiple where clause in LINQ?

Filter collections using Where clause in C#. A single query expression may have multiple where clauses.

Is LINQ faster than for each?

LINQ is not faster than For Each - dispelling the myth of avoiding For Each.

Is LINQ faster than lambda?

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.


2 Answers

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);
like image 106
Luke Merrett Avatar answered Oct 02 '22 02:10

Luke Merrett


First Where returns IQueryable<T> so there will be no performance difference.

like image 29
empi Avatar answered Oct 02 '22 01:10

empi