Linq join - group by - OrderByDescending查询

时间:2018-02-09 09:51:08

标签: c# linq join group-by

我有这个问题:

from i in dc.TFFiles                    
where i.Tid == tid
group i by new { i.Title, i.Type } into gr
select gr.OrderByDescending(g => g.Version).First();

我想在另一个表中添加一个连接,这样我就可以访问第二个表的字段

这是我需要的加入,而不是group by

from i in dc.TFFiles
join c in dc.FCategory on i.CatId equals c.id 
....

如何将group by查询与join

结合起来

尝试过这样但是没有按版本降序排序结果。即使有更高版本的文件,我总是得到版本1。

var result =
                    from i in dc.TFFiles                    
                    where i.Tid == tid                    
                    group i by new { i.Title, i.Type } into gr
                    orderby gr.FirstOrDefault().Version descending
                    join c in dc.FCategories on gr.FirstOrDefault().CatId equals c.Id
                    select new { id = gr.FirstOrDefault().id, Title = gr.FirstOrDefault().Title, Version = gr.FirstOrDefault().Version };

1 个答案:

答案 0 :(得分:1)

也许你可以试试:

var result =
                    from i in dc.TFFiles                    
                    where i.Tid == tid                    
                    group i by new { i.Title, i.Type } into gr
                    join c in dc.FCategories on gr.FirstOrDefault().CatId equals c.Id
                    select new { id = gr.FirstOrDefault().id, Title = gr.FirstOrDefault().Title, Version = (from cv in gr select cv.Version).Max() };