开发者

OrderBy and Distinct using LINQ-to-Entities

开发者 https://www.devze.com 2022-12-22 23:27 出处:网络
Here is my LINQ query: (from o in entities.MyTable orderby o.MyColumn select o.MyColumn).Distinct(); Here is the result:

Here is my LINQ query:

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

Here is the result:

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

Here is t开发者_高级运维he generated 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?


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

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


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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消