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 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).
精彩评论