Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq How to use where correctly

Tags:

c#

linq

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();
like image 705
kojirosan Avatar asked Dec 08 '22 05:12

kojirosan


1 Answers

There is no functional difference because daisy-chaining Where calls is a logical AND operation, and you are currently ANDing 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 Where as opposed to just one enumerator. (apologies, that part was only for Linq to Objects.)

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.

like image 66
Adam Houldsworth Avatar answered Dec 11 '22 07:12

Adam Houldsworth