Stacking where conditions with Lambda expressions

Viewed 87

We generally add multiple conditions in Where expression separating with &&(||).

Suppose, if I stack multiple where conditions is there any difference in performance?

For example:

Is this line

dbContext.Students.Where(s=> s.Section = 5 && s.Marks >50).ToList();

Similar to

dbContext.Students.Where(s=>s.Section = 5).Where(s=>s.Marks > 50).ToList();

Note: Above line is possible as Where returns IQueryable which inturn has Where.

3 Answers

The time your statement hits the db is when .ToList() is called. Hence what you do before that wouldn't create much difference in practice.

However from the perspective of pure mathematical performance, there should be some difference related with the translation process going behind those. Which can be understood by an experiment as @sujith karivelil suggests, or by some deep reading.

I think that using '&&' and '||' operators instead of multiple clauses essentially results in 1 enumeration over the full collection once. Multiple 'Where' clauses means you will enumerate over the full collection, then the results, which could be the full collection again.

I would suggest the use operator "&&" .. Because its filter the records at a single moment even used multiple condition. But if you use multiple where statements it definitely impact the performance because how many times you used where statement it hit the result query for filtering.

Related