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

提前致谢

最佳答案

我不知道是否有帮助,但是您可以尝试这样的方法;

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();

关于c# - LINQ到SQL Distinct和orderby,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4318909/

10-17 02:36