Does the where clause in the where clause in the LINQ query question support order?

I am new to LINQ. Can someone clarify the question of whether the order of conditions is in the where section of the LINQ question.

for example: is there a difference in wrt performance between two requests

Request-1

from prod in Products where prod.ExpiryDate == Products.Where(s => s.ID.Equals(CurrObj.Id) && s.Type.Equals(CurrObj.Type)).Max(s => s.ExpiryDate) && prod.ID.Equals(CurrObj.Id) && prod.Type.Equals(CurrObj.Type) select new { AmountFrom = prod.AmountFrom, AmountTo = prod.AmountTo } 

Request 2

 from prod in Products where prod.ID.Equals(CurrObj.Id) && prod.Type.Equals(CurrObj.Type) && prod.ExpiryDate == Products.Where(s => s.ID.Equals(CurrObj.Id) && s.Type.Equals(CurrObj.Type)).Max(s => s.ExpiryDate) select new { AmountFrom = prod.AmountFrom, AmountTo = prod.AmountTo } 

Change I just measured the performance. Query-1 takes about 900 ms, while Query-2 takes 350 ms.

+5
source share
2 answers

If it is LINQ-To-Objects, this is important.

Enumerable.Where comparable to an if clause. So this is ...

 if(expensiveMethodThatReturnsBool() && num1 < num2) { // ... } 

... is probably less effective than:

 if(num1 < num2 && expensiveMethodThatReturnsBool()) { // ... } 

because && is a short circuit operator. The second expression is evaluated only on the first return true . The same applies to || , the second is evaluated only if the first returned is false .

7.11 Conditional logical operators


He looks like a chained Where s. Similarly, because predicates apply to every remaining element that has passed through the previous Where .

So this is ...

 .Where(x => expensiveMethodThatReturnsBool(x)) .Where(x => x.num1 < x.num2) 

may also be less effective than:

 .Where(x => x.num1 < x.num2) .Where(x => expensiveMethodThatReturnsBool(x)) 

The first is logically equivalent:

 .Where(x => expensiveMethodThatReturnsBool(x) && x.num1 < x.num2) 
+5
source

Think carefully, yes, since they are all generated as SQL at the end, two different SQL statements will be different, now in certain situations the order of things is in the sql question, but you cannot say for sure if you are not measuring it.

I suggest noy to worry about this until you come across or know something for sure when measuring performance.

+1
source

Source: https://habr.com/ru/post/1200726/


All Articles