使用 c# 在 linq 中使用 max 并连接在一起
我有一个主从表,我想获取主连接与详细信息的列表,其中某些字段中的详细信息是最大的。 例如,我有一个名为 Document 的表,还有一个名为 Revision 的子表。我想获取文档联接修订的列表,其中提交的修订为 max ? 一种解决方案是:
using ( ProcurementDataContext dc = new ProcurementDataContext() )
{
var temp = from ddr in dc.E_DesignDocumentRevisions
group ddr by ddr.DesignDocumentID into g
select new { MaxRevision = g.Max(x => x.Revision), g.Key };
var result = from t in temp
join ddr in dc.E_DesignDocumentRevisions
on new { DesignDocumentID = t.Key, Revision = t.MaxRevision } equals new { ddr.DesignDocumentID, ddr.Revision }
join dd in dc.E_DesignDocuments
on ddr.DesignDocumentID equals dd.ID
where dd.DesignDocumentTypeID == DesignDocumentTypes.MR
select new { ddr.ID, dd.DocumentNumber };
foreach (var item in result )
{
dic.Add(item.ID, item.DocumentNumber.ToString());
}
}
如何在一个查询中做到这一点?
I have a master-detail tables and I want to get list of master join with detial where detail is max in some filed.
for example I have a table named Document and also a child table named Revision .I want to get list of document join Revision where Revision filed is max
?
One solution is:
using ( ProcurementDataContext dc = new ProcurementDataContext() )
{
var temp = from ddr in dc.E_DesignDocumentRevisions
group ddr by ddr.DesignDocumentID into g
select new { MaxRevision = g.Max(x => x.Revision), g.Key };
var result = from t in temp
join ddr in dc.E_DesignDocumentRevisions
on new { DesignDocumentID = t.Key, Revision = t.MaxRevision } equals new { ddr.DesignDocumentID, ddr.Revision }
join dd in dc.E_DesignDocuments
on ddr.DesignDocumentID equals dd.ID
where dd.DesignDocumentTypeID == DesignDocumentTypes.MR
select new { ddr.ID, dd.DocumentNumber };
foreach (var item in result )
{
dic.Add(item.ID, item.DocumentNumber.ToString());
}
}
How can I do that in just one query?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
理论上来说,在您需要枚举结果之前,由于延迟执行,它仍然是一个查询。当您迭代结果时,将执行查询,因此与将查询分成较小的块相比,对性能的影响非常小。
但是,如果您只想合并两个块,则可以将第一个块叠瓦到第二个块中:
Well in theory until you demand the result of the enumeration it is still one query due to deferred execution. The query will be executed when you iterate over the result, so theres very few impact performance-wise compared to separating queries into smaller blocks.
However, if youre looking to just merge both blocks, you can just imbricate the first one into the second:
坦克为您提供帮助。您是对的,但我找到了一种使用非常小的查询的好方法:
当我们在 Group by 子句中使用某些表(多个)中的文件时,linq 会将它们连接到生成的查询中。再次坦克
Tanks for your help .You are right ,but I found a great way with very smaller query:
When we use fileds from some tables(more than one) in Group by clause linq will join them in generated query . Tanks again