0

I want to get records with parentIds. But this Linq expression gave me elements with 0 parentId value.

var orders =
 OrderEquityTransactions.AsParallel().Where(
 o => o.FinancialInstrumentId == financialInstrumentPrice.FinancialInstrumentId &&
 o.ParentId != 0 &&
 o.DebitCredit == "A" ? o.Price >= financialInstrumentPrice.Price : o.Price <= financialInstrumentPrice.Price).ToList();

After some digging I rewrote expression with additional two brackets and problem solved.

var orders =
 OrderEquityTransactions.AsParallel().Where(
 o => o.FinancialInstrumentId == financialInstrumentPrice.FinancialInstrumentId &&
 o.ParentId != 0 &&
 (o.DebitCredit == "A" ? o.Price >= financialInstrumentPrice.Price : o.Price <= financialInstrumentPrice.Price)).ToList();

What is the reason of this behavior?

asked Dec 8, 2015 at 7:29
1
  • 2
    Operator precedence? Commented Dec 8, 2015 at 7:31

2 Answers 2

4

Because in the first case it was interpreted as:

o => (o.FinancialInstrumentId == financialInstrumentPrice.FinancialInstrumentId 
 && o.ParentId != 0 && o.DebitCredit == "A") 
 ? o.Price >= financialInstrumentPrice.Price 
 : o.Price <= financialInstrumentPrice.Price

which is absolutely another.

Please, read this article on operator precedence.
Ternary conditional operator has the lower priority than conditional AND.

answered Dec 8, 2015 at 7:31
Sign up to request clarification or add additional context in comments.

Comments

3

As per Operator precedence and associativity, conditional ANDs have a higher precedence than the conditional operator. So C# evaluates your expresion like this:

(o.FinancialInstrumentId == financialInstrumentPrice.FinancialInstrumentId 
 && o.ParentId != 0 && o.DebitCredit == "A")
 ? o.Price >= financialInstrumentPrice.Price
 : o.Price <= financialInstrumentPrice.Price
answered Dec 8, 2015 at 7:32

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.