c# - 对使用 OrderBy 的 linq 查询进行分页

标签 c# linq entity-framework

我想返回按特定属性分组的特定实体的列表,按时间戳降序排列并分页(使用 Skip 和 Take)。我得到的是这个:

container.CoinMessageSet.Where(
                c => c.MessageState != MessageStateType.Closed &&
                     (c.DonorOperator.OperatorCode.Equals("opcode") ||
                      c.RecipientOperator.OperatorCode.Equals("opcode"))
                ).OrderByDescending(c => c.TimeStamp)
                 .GroupBy(c => c.Reference).Skip(x).Take(100);

执行后我得到了异常:

The method 'Skip' is only supported for sorted input in LINQ to Entities. 
The method 'OrderBy' must be called before the method 'Skip'.

...我调用了 OrderBy()(尽管是降序)并且我在 Skip() 之前调用了它!我错过了什么?

最佳答案

您还没有订购这些团体;您需要先完成此操作,然后才能进行分页。例如:

.GroupBy(c => c.Reference).OrderBy(grp => grp.Key).Skip(x).Take(100);

(如果您希望组的顺序相反,您也可以替换为 OrderByDescending)

另外:因为你在分组,所以原始数据中的顺序在很大程度上是没有意义的;您可能会删除 OrderByDescending(c => c.TimeStamp)

所以最终结果:

var query = container.CoinMessageSet.Where(
            c => c.MessageState != MessageStateType.Closed &&
                 (c.DonorOperator.OperatorCode.Equals("opcode") ||
                  c.RecipientOperator.OperatorCode.Equals("opcode"))
            ).GroupBy(c => c.Reference).OrderBy(grp => grp.Key)
             .Skip(x).Take(100);

或者可能:

var query = (from c in container.CoinMessageSet
             where c.MessageState != MessageStateType.Closed &&
                  (c.DonorOperator.OperatorCode == "opcode" ||
                   c.RecipientOperator.OperatorCode == "opcode")
             group c by c.Reference into grp
             orderby grp.Key
             select grp).Skip(x).Take(100);

关于c# - 对使用 OrderBy 的 linq 查询进行分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14213971/

相关文章:

c# - C# 中的不可变类型和属性

c# - Linq 到 SQL 连接

c# - Linq 选择加入

c# - ViewModel 更新 - 保存前更改属性

security - Entity Framework 安全和注入(inject)

c# - .NET Core 中的 FTP 客户端

c# - 数据绑定(bind)到 ComboBox 中的 CollectionViewSource 时如何保留 CurrentItem 的双向绑定(bind)

c# - 来自 Azure Blob 下载图像的链接,但我只需要观看(Asp.NET Core)

c# - linq查询选择特定值的所有元素但没有其他值

c# - 如何通过 Entity 框架自动为 Oracle 数据库生成标识?