我正在试着找出一种更简单的方法,我可以将以下代码压缩到尽可能少的几行中。理想情况下,我希望从中得到一个IDictionary>。
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);
}
}
}理想情况下,我想这样做:
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...发布于 2013-06-23 11:43:22
这应该是等效的:
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);备注:
.Select(rid => rid.Id == reportId),但我假设它应该是Where而不是Select,否则您最终将得到一个null集合,因为Select结果将是bool类型,并且as Report将为每个结果输出< code >D10。SubReportItems的Title是唯一的时才有效。可以想象,一个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对象。
https://stackoverflow.com/questions/17257503
复制相似问题