当使用DISTINCT时,LINQ to SQL不会生成ORDER BY排序语句?

14

以下基本的LINQ to SQL语句无法按照orderby排序。从T-SQL中可以看出,没有进行排序。你知道为什么吗?

LINQ to SQL:

      var results = (from stats in db.t_harvest_statistics
                       orderby stats.unit_number
                       select stats.unit_number).Distinct().ToList();

以上结果对应以下 TSQL

SELECT 
[Distinct1].[unit_number] AS [unit_number]
FROM ( SELECT DISTINCT 
[Extent1].[unit_number] AS [unit_number]
FROM [dbo].[t_harvest_statistics] AS [Extent1]
     )  AS [Distinct1]

unit_number 是一个标识列吗? - asawyer
不,unit_number不是身份标识。它是一个int数据类型。 - KeelRisk
2个回答

29

这是 SQL 和关系代数的一个限制,即 ORDER BY 与 DISTINCT 的关系。

由于 ORDER BY 是一种视图操作,因此它必须在 SQL 中“更外层”(在“顶层”)进行。虽然可以编写将 ORDER BY 与 RA 操作“更内层”相关联的 SQL,但通常会导致未定义行为(有时有效)。因此,Linq2Sql 可以自由地忽略 ORDER BY,尽管也许使用异常会更好……无论如何,这样做会更不难察觉;-)(实际上,任何未提供“更严格”Distinct 定义的 Linq 提供程序都存在此问题。)

删除 Distinct(),Linq2Sql 就会按预期生成 ORDER BY。解决方案只是切换操作顺序,使 ORDER BY 再次位于“顶层”。

这在文章 Use of Distinct and OrderBy in LINQ 中有所涉及:

This behavior might appear strange. The problem is that the Distinct operator does not grant that it will maintain the original order of values. Applied to LINQ to SQL, this mean that a sort constraint can be ignored in the case of a query like queryA.

The solution is pretty s[i]mple: put the OrderBy operator after the Distinct one, like in the following queryB definition:

var queryB = 
    (from o in db.Orders
     select o.Employee.LastName)
    .Distinct().OrderBy( n => n );

编程愉快。


1
@KeelRisk OrderBy 需要一些东西,因为没有 OrderBy() 的重载(如果存在的话,将以相同的方式定义)。我猜 OrderByYeSelf 的情况并不特别;-) - user166390

0

我在对交易表按年份排序时遇到了同样的问题。

试试这个

 var results = (from stats in db.t_harvest_statistics
                       select stats.unit_number).Distinct().OrderBy(x =(Int16)x.unit_number).ToList();

获取不同的值后使用orderby方法


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接