linq to sql Distinct和orderby

Ian*_*Ian 32 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();
Run Code Online (Sandbox Code Playgroud)

上面的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]
Run Code Online (Sandbox Code Playgroud)

我本以为下面的sql更清晰,但我不确定实现它的linq语句.

select distinct 
    o.ProgramID, 
    t.Program 
from 
    table1 0 
    inner join table2 t on t.ProgramID = o.ProgramID 
order by t.Program
Run Code Online (Sandbox Code Playgroud)

提前致谢

Ale*_*dez 30

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

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();
Run Code Online (Sandbox Code Playgroud)


use*_*040 11

我试过这个并且有效:

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); 
Run Code Online (Sandbox Code Playgroud)

首先你做Distinct然后OrderBy,然后OrderBy工作.


Mar*_*ell 5

分析两个查询,比较 stats-IO 和实际执行计划。完全有可能对SQL服务器造成零差异。

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