Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OrderBy and Distinct using LINQ-to-Entities

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 the 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?

like image 923
BlueRaja - Danny Pflughoeft Avatar asked Mar 12 '10 20:03

BlueRaja - Danny Pflughoeft


2 Answers

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);
like image 157
mmx Avatar answered Sep 21 '22 22:09

mmx


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).

like image 30
Amy B Avatar answered Sep 23 '22 22:09

Amy B