What's the difference between this 2 queries?
Aren't they same and which one is speedy? Will be any problem using where after where? Writing where after where makes my code my readable for me. Am i doing this wrong?
First query:
Model= (model.Where(p => p.Date.Year == yilim)
.Where(p => p.Id== 2 || p.Id== 3)
.OrderBy(m => m.Date.Month))
.ToList();
Second Query:
Model= (model.Where(p => p.Date.Year == yilim && (p.Id== 2 || p.Id== 3))
.OrderBy(m => m.Date.Month))
.ToList();
There is no functional difference because daisy-chaining Where
calls is a logical AND
operation, and you are currently AND
ing stuff the two separate conditions together.
However, it will likely be slightly less efficient in terms of removing ability for the compiler to optimise the condition checking (such as short-circuiting) and the additional enumerator required for the second (apologies, that part was only for Linq to Objects.)Where
as opposed to just one enumerator.
If your code was to OR
the conditions, only the second query would provide what you want:
Model= (model.Where(p => p.Date.Year == yilim || p.Id== 2 || p.Id== 3)
.OrderBy(m => m.Date.Month))
.ToList();
// Cannot express the above query in simple daisy-chained Where calls.
If the logic in a Where
is becoming difficult to read, try "commentless coding" and stuff the condition into a method with a very readable name, then you can do .Where(x => TheCustomerNameIsValid(x))
, or method grouping it .Where(TheCustomerNameIsValid)
(when you can). This also helps with debugging, because placing breakpoints in a method is a little less finicky than doing so in a lambda.
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