用户登录
用户注册

分享至

linq to sql Distinct 和 orderby

  • 作者: 今后丶何如
  • 来源: 51数据库
  • 2022-12-13

问题描述

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(下面)并没有想象中的那么简单

the above linq statement actually returns the correct result, but he sql generated (below) is not as simple as it could be

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 语句来实现它.

I would have thought the sql below is far cleaner but I'm not sure of the linq statement to achieve it.

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

提前致谢

推荐答案

不知道会不会有帮助,不过你可以试试这样的;

I don't know if it will help, but you can try something like this;

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();
软件
前端设计
程序设计
Java相关