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?
-
2Operator precedence?Frédéric Hamidi– Frédéric Hamidi2015年12月08日 07:31:35 +00:00Commented Dec 8, 2015 at 7:31
2 Answers 2
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.
Comments
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