c# - .NET : LINQ's Last()

标签 c# linq

我是 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/

相关文章:

c# - 选择带有两个下拉列表的选择

c# - native C# 支持检查 IEnumerable 是否已排序?

c# - 如何使用 EF Core 3.0 使多个包含更高效

linq - 使用 LINQ 连接两个表并将多个记录作为一行返回

c# - 从 linq to sql 中的子查询中选择前 1 个结果

c# - 将 soap XML 解析为 C# 类

c# - 如何从 dll 中反编译/提取 (cshtml--(razor view))

c# - Rebus:2 个进程中的 2 个处理程序。击球不一致且交替

c# - 依赖注入(inject)和 AppSettings

c# - Xamarin - 现在已过时的 ParentView 的替代方案