首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >棘手的LINQ和嵌套集合

棘手的LINQ和嵌套集合
EN

Stack Overflow用户
提问于 2013-06-23 11:35:01
回答 1查看 92关注 0票数 1

我正在试着找出一种更简单的方法,我可以将以下代码压缩到尽可能少的几行中。理想情况下,我希望从中得到一个IDictionary>。

代码语言:javascript
复制
 var report = db.Reports.Select(rid => rid.ID == reportId) as Report;
 Dictionary<string, List<string>> notes = new Dictionary<string, List<string>>();
 foreach (var subreport in report.SubReports)
 {
   foreach (var subreportitem in subreport.SubReportItems)
   {
     notes[subreportitem.Title] = new List<string>();
     foreach (var note in subreportitem.SubReportItemNotes)
     {
        notes[subreportitem.Title].Add(note.NoteDetails); 
     }
   }
 }

理想情况下,我想这样做:

代码语言:javascript
复制
from report in db.Reports
where report.ID == reportId
from subreports in report.SubReports
from subreportitems in subreports.SubReportItems
from notes in subreportitems.SubReportItemNotes
//Unsure how to select into the desired dictionary...
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-06-23 11:43:22

这应该是等效的:

代码语言:javascript
复制
db.Reports
    .Where(rpt => rpt.ID == reportId)
    .Cast<Report>()
    .SelectMany(rpt => rpt.SubReports)
    .SelectMany(subRpt => subRpt.SubReportItems)
    .ToDictionary(
        sri => sri.Title, 
        sri => sri.SubReportItemNotes.SelectMany(note => note.NoteDetails);

备注:

  1. 您代码的第一行使用.Select(rid => rid.Id == reportId),但我假设它应该是Where而不是Select,否则您最终将得到一个null集合,因为Select结果将是bool类型,并且as Report将为每个结果输出< code >D10。
  2. 仅当所有SubReportItemsTitle是唯一的时才有效。可以想象,一个Report可以具有10个SubReports,并且在这些SubReports中存在具有相同SubReportItems的两个或更多个Title。如果是这种情况,那么您可能需要重新考虑一下这一点,否则当您尝试添加字典中已有的DuplicateKeyException时,您将得到一个Title

解释:

基本上,我们获取了一组报告,并应用了这样的条件:我们只需要ID为所需ID的报告。就我个人而言,我会将其放在单独的一行中,并使用SingleOrDefault而不是Where,因为我只期望一个结果。

接下来,我们调用.Cast<Report>只是因为您正在使用as Report,所以我猜您需要它。这在实践中可能是多余和不必要的。

第一个.SelectMany调用将获取所有Reports的所有SubReports。同样,在这一点上,我们可能只有一个Report对象。

现在我们有一堆SubReports,但是我们真的想获得所有的SubReportItems,所以我们使用另一个SelectMany来获得它们。

现在我们有了来自所有(1)个SubReportItem的所有SubReport的所有Report,现在我们创建字典。对于每个SubReportItem,我们从Title属性创建一个键,然后对于该值,我们使用最后一个SelectMany来获取与所有当前SubReportItemNote相关联的所有NoteDetails对象。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17257503

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档