LINQ:列出最大值

时间:2018-07-30 14:17:05

标签: asp.net-mvc linq asp.net-mvc-5

我在SQL Server中有此查询

select max(win_votos), win.cdt_id, cdt_nome 
   from tb_ganhadores_win as win
   inner join tb_candidatos_cdt as cdt on cdt.cdt_id = win.cdt_id
   group by win.cdt_id,cdt_nome

<-

我需要创建一个列表“ AspNetMvc”页面,例如

public ActionResult ListWinners(int? id){

LINQ QUERY HERE

return View('that list');

}

对不起我的英语

有人可以帮我吗?

2 个答案:

答案 0 :(得分:0)

如果您使用实体框架,并且您的模型名称是这样的,则可以使用这样的想法:

var result =  from win in tb_ganhadores_win
              join cdt in tb_candidatos_cdt on cdt.cdt_id = win.cdt_id
              group win by new { win.cdt_id, cdt_nome } into g
                select new
                {
                    max = g.Max(win_votos),
                    win.cdt_id,
                    cdt_nome
                };

并返回result.ToList();

注意:

  

“ tb_ganhadores_win”

  

“ tb_candidatos_cdt”

是您的模型。根据需要替换它

答案 1 :(得分:0)

var res= (from win in dbContext.tb_ganhadores_wins
          join cdt in dbContext.tb_candidatos_cdts
          on win.cdt_id equals cdt.cdt_id
          select new {win,cdt})
          .GroupBy(x=>new{Id=x.win.cdt_id,Nome=x.cdt.cdt_nome})
          .Select(x=>new
                     {
                       Votos=x.Max(z=>z.win.win_votos),
                       Id=x.Key.Id,
                       Nome=x.Key.Nome
                     })
         .ToList();