linq to sql Distinct和orderby

时间:2010-11-30 21:33:22

标签: c# linq-to-sql

var result = table1.Join(table2, o => o.ProgramID, t => t.ProgramID, (o, t) => new { o.ProgramID, t.Program })
         .OrderBy(t => t.Program)
         .Distinct();

上面的linq语句实际上返回了正确的结果,但是他生成的sql(下面)并不是那么简单

SELECT [t2].[ProgramID], [t2].[Program]
FROM (
    SELECT DISTINCT [t0].[ProgramID], [t1].[Program]
    FROM [table1] AS [t0]
    INNER JOIN [table2] AS [t1] ON [t0].[ProgramID] = [t1].[ProgramID]
    ) AS [t2]
ORDER BY [t2].[Program]

我原本以为下面的sql更干净但我不确定实现它的linq语句。

select distinct 
    o.ProgramID, 
    t.Program 
from 
    table1 0 
    inner join table2 t on t.ProgramID = o.ProgramID 
order by t.Program

提前致谢

3 个答案:

答案 0 :(得分:28)

我不知道它是否会有所帮助,但你可以尝试这样的事情;

var result = (from o in table1
              join t in table2 on o.ProgramID equals t.ProgramID
              orderby t.Program
              select new { o.ProgramID, t.Program }).Distinct();

答案 1 :(得分:10)

我试过这个并且有效:

var result = (from o in table1
              join t in table2 on o.ProgramID equals t.ProgramID
              select new { o.ProgramID, t.Program })
              .Distinct().OrderBy(t => t.Program)
                         .ThenBy(t => t.ProgramName)
                         .ThenBy(t => t.Description); 

首先你做了Distinct然后是OrderBy,然后OrderBy工作。

答案 2 :(得分:4)

描述两个查询,比较stats-IO和实际执行计划。它完全有可能与SQL服务器没有区别。

如果您真的想知道TSQL,请使用ExecuteQuery-of-T并自行传递TSQL。也许包括一些锁定提示(最常见的是:NOLOCK)