奇怪LINQ行为
问题描述:
我有这样的代码:奇怪LINQ行为
在这里我从数据库中获取多头的列表:
IQueryable<long> query = from t in table select t.LongId
在这里,我尝试从这些ID获得最大的:
long max = query.Any() ? query.Max() : 0;
但无论查询的结果是多少,max始终设置为0.
你有什么想法w HY?
答
如果
long max = query.Any() ? query.Max() : 0;
回报为零,则以下条件之一为真:
- 查询不返回任何结果
- 查询结果中的最大值为零
当您在定义查询和从查询中获取最大值之间修改表时,可能会出现第一种情况。请记住 - 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
答
难道这不是更简单吗?
long max = table.OrderByDescending(t => t.LongId)
.Select(t => t.LongId)
.FirstOrDefault() ?? 0;
答
最简单的方法:
var maxId = table.OrderByDescending(x => x.LongId).First().LongId;
如何调试呢? query.Any()返回什么,query.Max()返回什么? – nvoigt
1)这两行之间是否有其他代码? 2)什么是“表”和它有什么数据? –
你确定查询不是空的吗? –