Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

?: 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?

like image 937
Marcus Avatar asked Dec 21 '22 23:12

Marcus


1 Answers

Your test expression is associating like this:

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

instead of like this:

x == "3" && (false ? false : true)
like image 189
Wesley Wiser Avatar answered Feb 07 '23 01:02

Wesley Wiser