Marcus
Marcus

Reputation: 5457

?: Conditional Operator in LINQ not working as expected

I'm having problems with one of my LINQ queries, so I made a simplified version of it in LINQPad to help me. Problem is, I don't understand why it's still not doing what I think it should...

var list = "1 2 3 4".Split();
var result = list.FirstOrDefault(x =>
                    x == "3"
                    && true);
result.Dump();

This gives back 3, just like one would assume.
However, when I run this:

var list = "1 2 3 4".Split();
var result = list.FirstOrDefault(x =>
                    x == "3"
                    && false ? false : true);

I get 1 back. The last line is the simplification of the actual code. Both examples should give true on the last line, which would return 3, but the query with the conditional operator is throwing a kink in there.

What am I missing?

Upvotes: 4

Views: 1831

Answers (4)

Roman Royter
Roman Royter

Reputation: 1665

I suspect your lambda evaluates to (x == 3 && false) ? false : true which will return the first element because the condition will always evaluate to false. Put parentheses for clearer code.

Upvotes: 0

payo
payo

Reputation: 4561

What you are seeing is due to operator precedence. A fix for you would be to wrap the condition in parens:

x == "3" && (false ? false : true)

&& has a higher precedence than ?:

Upvotes: 2

Louis Kottmann
Louis Kottmann

Reputation: 16638

it counts as (x == "3" && false) ? false : true which is why you have a strange behavior.

Upvotes: 1

Wesley Wiser
Wesley Wiser

Reputation: 9851

Your test expression is associating like this:

(x == "3" && false) ? false : true

instead of like this:

x == "3" && (false ? false : true)

Upvotes: 8

Related Questions