【问题标题】:Weird LINQ behaviour奇怪的 LINQ 行为
【发布时间】:2014-02-18 13:28:07
【问题描述】:

我有这个代码:

这里我从数据库中获取了 long 列表:

IQueryable<long> query = from t in table select t.LongId 

在这里我尝试从这些 ID 中获取最大值:

long max = query.Any() ? query.Max() : 0;

但是无论查询结果中有多少long,max总是设置为0。

你知道为什么吗?

【问题讨论】:

  • 调试一下怎么样? query.Any() 返回什么,query.Max() 返回什么?
  • 1) 这两行之间是否还有其他代码? 2)table是什么,有什么数据?
  • 您确定查询不为空吗?
  • 为什么要检查Any() 条件?另外 - 请不要仅仅因为他们没有解决您的问题而对 naswer 投反对票 - 这不是 SO 的工作方式。
  • 是的,我的错。不知何故,DefaultIfEmpty().Max() 感觉好多了,尽管他们的表现完全一样。

标签: c# linq if-statement ternary-operator


【解决方案1】:

如果

long max = query.Any() ? query.Max() : 0;

返回零,则以下之一为真:

  1. 查询不返回任何结果
  2. 查询结果中的最大值为零

当您在定义查询和从查询中获取最大值之间修改表时,第一种情况是可能的。请记住 - query 没有任何数据。它只是查询定义,只有在执行查询时才会得到数据(例如调用 Any() 或 Max())。

测试:

List<long> table = new List<long> { 1, 2, 3 };
var query = from t in table select t; // query is not executed
table.Clear(); // modify data source before query is executed
Assert.False(query.Any()); // execute query on modified data source

【讨论】:

    【解决方案2】:

    这不是更简单吗?

    long max = table.OrderByDescending(t => t.LongId)
                    .Select(t => t.LongId)
                    .FirstOrDefault() ?? 0;
    

    【讨论】:

      【解决方案3】:

      最简单的方法:

      var maxId = table.OrderByDescending(x => x.LongId).First().LongId;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多