我是 LINQ 和 LINQ to SQL 的新手,不明白这段代码有什么问题。我得到的 Excetpion.Message
是
"Query operator 'Last' is not supported."
我想做的是从最新的 100 个中获取最早的 LastActivityUtc
。代码如下。
var postTimes = from post in db.Post
where post.LastActivityUtc != null
orderby post.LastActivityUtc descending
select post.LastActivityUtc;
DateTime startDate = DateTime.MinValue;
if (postTimes.Count() >= 2)
{
startDate = postTimes.Take(100).Last().Value;
}
最佳答案
Brandon 发布了解决方案,但它需要在内存中复制整个列表。
如果您只是想从数据库查询“过渡”到进程中,您可以使用AsEnumerable
:
startDate = postTimes.Take(100).AsEnumerable().Last().Value;
话虽如此,您可能确实想要调用 ToList(),但更早 - 以避免必须为计数执行一次查询,为最后一个值执行一次查询:
var postTimes = (from post in db.Post
where post.LastActivityUtc != null
orderby post.LastActivityUtc descending
select post.LastActivityUtc).Take(100).ToList();
DateTime startDate = DateTime.MinValue;
if (postTimes.Count >= 2)
{
startDate = postTimes.Last().Value;
}
这将执行数据库查询一次,但只会将前 100 条记录提取到内存中。当然,如果您打算在其他地方使用 postTimes
,它会有所下降......
关于c# - .NET : LINQ's Last(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1262905/