Reputation: 465
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?
Upvotes: 0
Views: 64
Reputation: 388463
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
Upvotes: 3
Reputation: 34244
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.
Upvotes: 4