c# - 如何使用 Linq 订购集合属性?

标签 c# linq entity-framework asp.net-mvc-4 collections

Periods 是一个集合,其中包含每个 Period 的属性“periodStart”和“periodEnd”。 我需要根据每个 Period 的最后一个“periodEnd”的值对网格进行排序。

我认为下面的代码可以工作,......

var result = from sched in schedles
    orderby sched.Periods.Last().periodEnd descending
    select new Grid
    {
     ID = sched.ID,
     Name = sched.Name
    };

但我得到了错误 -->

Message: LINQ to Entities does not recognize the method '... Last[Period](System.Collections.Generic.IEnumerable`1[... Period])' method, and this method cannot be translated into a store expression.

我确信这对于更高级的开发人员来说是一个简单的问题,但我知道我缺少一些理解。 预先感谢任何可以帮助我理解此 orderby 语句的局限性的人。

最佳答案

有许多常见的 LINQ 方法是 not supported by LINQ to Entities . Last() 就是其中之一。如果你使用 First() 你会得到

The method 'First' can only be used as a final query operation.

所以你应该这样做

orderby sched.Periods.OrderByDescending(p => p.periodEnd)
             .FirstOrDefault().periodEnd

您必须按某些属性对 Period 进行排序,以告诉 EF “第一个”是什么。您可以在不防范空引用异常的情况下使用 FirstOrDefault(),因为整个表达式都被翻译成 SQL。它不会作为内存中的 LINQ 执行。

关于c# - 如何使用 Linq 订购集合属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21894980/

相关文章:

c# - Json.NET - 在 winforms 中反序列化和解析 json 数据

c# - 无法将 HashSet 转换为 IReadOnlyCollection

c# - 字符串拆分并将结果分布在不同的数组中

c# - EF 生成的 SQL 查询在查询日期时间列时返回空结果,但该记录存在于数据库中

mysql - Entity Framework : Set MySQL custom environment variables

c# - 如何以编程方式获取特定服务器标识

c# - Azure PDF Sharp 不使用 Unicode 字体

c# - 使用 LINQ 创建 JSON

c# - 使用 Group By 的 LINQ 查询

c# - 使用 C#/Moq 框架模拟带有输入参数的异步 DbContext 函数