.NET:LINQ的Last()

9 c# linq

我是LINQ和LINQ to SQL的新手,并不明白这段代码有什么问题.在Excetpion.Message我得到的是

"不支持查询运算符'Last'."

我要做的是从LastActivityUtc最新的100中获得最早的代码.代码如下.

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;
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 19

Brandon发布了一个解决方案,但它需要将整个列表复制到内存中.

如果您只想从数据库查询"转换"到进程内,可以使用AsEnumerable:

startDate = postTimes.Take(100).AsEnumerable().Last().Value;
Run Code Online (Sandbox Code Playgroud)

说了这么多,你可能需要调用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;
}
Run Code Online (Sandbox Code Playgroud)

这将执行一次数据库查询,但只将前100条记录提取到内存中.当然,如果你打算在postTimes其他地方使用它会有所下降......

  • 谁更愚蠢?傻瓜,还是追随他的傻瓜? (2认同)