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/