LINQ - Order By 和 Distinct by 不同的字段。跳过并采用不同的值

LINQ - Order By and Distinct by different fields. Skip & Take distinct values

我正在尝试 ORDER BY 一些字段,但 SELECT DISTINCT 另一个字段,然后应用 Skip & Take

代码:

var result = entities.OrderBy(e => e.OrderField)
                     .Select(e => e.SelectField)
                     .Distinct()
                     .Skip(skip)
                     .Take(take)
                     .ToArray();

但是我遇到了这个异常:

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

我理解原因(集合在排序和跳过之间改变)但是我可以解决这个问题而不需要多次查询数据库(编辑:并且不获取比预期更多的实体)吗?

编辑: 我认为没有最佳解决方案,所以我所做的是获取值然后对它们进行分页。 *叹息*

var result = entities.OrderBy(e => e.OrderField)
                     .Select(e => e.SelectField)
                     .Distinct()
                     .ToArray()
                     .Skip(skip)
                     .Take(take)
                     .ToArray();

您可以从数据库中获取 Distinct 值,然后像这样在内存中工作:

var result = entities.OrderBy(e => e.OrderField)
                     .Select(e => e.SelectField)
                     .Distinct()
                     .ToArray()
                     .Skip(skip)
                     .Take(take)
                     .ToArray();

想查询就查询一次

您应该在 Skip 之前添加 .OrderBy(e => e)

var result = entities.OrderBy(e => e.OrderField)
                 .Select(e => e.SelectField)
                 .Distinct()
                 .OrderBy(e => e)
                 .Skip(skip)
                 .Take(take)
                 .ToArray();

阅读以下内容post以加深理解

The method 'Skip' is only supported for sorted input in LINQ to Entities

编辑: 根据评论更新。 以下代码应该适用于您的情况:

var result = entities
            .OrderBy(e => e.OrderField)
            .Select(e => e.SelectField)
            .GroupBy(e => e)
            .Select(group => group.Key)
            .Skip(skip)
            .Take(take)
            .ToArray();