使用LINQ到实体的OrderBy和Distinct

时间:2022-11-30 18:01:20

Here is my LINQ query:

这是我的LINQ查询:

(from o in entities.MyTable
orderby o.MyColumn
select o.MyColumn).Distinct();

Here is the result:

结果如下:

{"a", "c", "b", "d"}

Here is the generated SQL:

这是生成的SQL:

SELECT 
[Distinct1].[MyColumn] AS [MyColumn]
FROM ( SELECT DISTINCT 
    [Extent1].[MyColumn] AS [MyColumn]
    FROM [dbo].[MyTable] AS [Extent1]
)  AS [Distinct1]

Is this a bug? Where's my ordering, damnit?

这是一个错误吗?我的订单在哪里,该死的?

2 个解决方案

#1


10  

You should sort after Distinct as it doesn't come with any guarantee about preserving the order:

您应该在Distinct之后排序,因为它没有任何关于保留订单的保证:

entities.MyTable.Select(o => o.MyColumn).Distinct().OrderBy(o => o);

#2


1  

This question discusses the rules for Linq to Objects: Preserving order with LINQ

这个问题讨论了Linq to Objects的规则:使用LINQ保留顺序

In the database, even fewer operations preserve order. No one anywhere preserves order when Distinct'ing (as generally a Hash algorithm is used).

在数据库中,更少的操作保留了订单。当Distinct'ing(通常使用Hash算法)时,没有人能保持秩序。

#1


10  

You should sort after Distinct as it doesn't come with any guarantee about preserving the order:

您应该在Distinct之后排序,因为它没有任何关于保留订单的保证:

entities.MyTable.Select(o => o.MyColumn).Distinct().OrderBy(o => o);

#2


1  

This question discusses the rules for Linq to Objects: Preserving order with LINQ

这个问题讨论了Linq to Objects的规则:使用LINQ保留顺序

In the database, even fewer operations preserve order. No one anywhere preserves order when Distinct'ing (as generally a Hash algorithm is used).

在数据库中,更少的操作保留了订单。当Distinct'ing(通常使用Hash算法)时,没有人能保持秩序。