C#加入组查询
我正在使用此查询:C#加入组查询,c#,linq-to-sql,C#,Linq To Sql,我正在使用此查询: 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
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() };
但如果存在以下文件:
id | tid | Title | Type | Version
0 | 15 | File1 | Type1 | 0
1 | 15 | File2 | Type1 | 0
2 | 15 | File1 | Type1 | 1
3 | 15 | File1 | Type1 | 2
我会回来的:
id | tid | Title | Type | Version
0 | 15 | File1 | Type1 | 2 (wrong version - id)
1 | 15 | File2 | Type1 | 0
而不是:
id | tid | Title | Type | Version
3 | 15 | File1 | Type1 | 2 (correct version - id)
1 | 15 | File2 | Type1 | 0
如何更改查询以获得正确的结果?我在评论中的第一个建议是获取最大id,但这可能会返回错误的id 第二项建议是使用以下内容:
id = gr.OrderByDescending(item => item.Version).FirstOrDefault().id
它将使用降序排序从具有最高版本的组中获取id
还有一件事:如果有相同的记录,其中只有id不同,那么返回的id可能不是最后一个。假设这不是问题。您不能选择最大id吗?或者在某些情况下,这会返回错误的结果?我想选择具有最大版本的文件,因为我不确定获取的最大id是否总是正确的。那么,这样做如何:
id=gr.OrderByDescending(item=>item.Version).FirstOrDefault().id
@pritaeas这是有效的!如果你想把它贴出来作为回答,就接受它