c# - ? : Conditional Operator in LINQ not working as expected

标签 c# linq conditional conditional-operator

我的一个 LINQ 查询有问题,所以我在 LINQPad 中制作了一个简化版本来帮助我。问题是,我不明白为什么它仍然没有按照我认为应该的方式进行......

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

这返回 3,就像人们假设的那样。
但是,当我运行它时:

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

我得到了1。最后一行是实际代码的简化。这两个示例都应在最后一行给出 true,这将返回 3,但使用条件运算符的查询会在那里引发问题。

我错过了什么?

最佳答案

你的测试表达式是这样关联的:

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

而不是像这样:

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

关于c# - ? : Conditional Operator in LINQ not working as expected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10198528/

相关文章:

c# - 如果列表为空,则添加默认字符串

c - 如何在 printf 语句中设置条件?

c# - 如何在启用 ASP.NET Core 2.2 EndpointRouting 的情况下使用 RouteDataRequestCultureProvider?

c# - HttpContext.Current.Items ["value"] 不工作因为 AngularJS 调用创建新 session

c# - IF 语句需要分号

c# - 如何使用 LINQ 对多个字段进行排序?

linq - Entity Framework (4.2)HasRequired导致意外的LEFT OUTER JOIN

ruby-on-rails - "one, other or both"案例的更好解决方案

java - 提供不是 boolean 值的循环条件

c# - Windows Phone 7 - iCal 生成器 - C#