LINQ和嵌套结构中的数据组 [英] LINQ and group by data nested within a structure
问题描述
我有大致看起来像这样的结构:
I have a structure that roughly looks like this:
List<ProductLine> -> ID
Name
...
List<LineOfBusiness> -> ID
Name
...
List<Watchlist> -> ID
Name
ReportCount
一个监视列表中可以在多个高吊球,但ReportCount存在将只用于该业务线为监视列表之下的报告计数。我需要他们在结构这种方式,因为一个LOB内有多少报道存在一个给定的监视列表中的计数是很重要的其他地方。
A Watchlist can exist under multiple LoBs but the ReportCount will only be for the count of reports that exist under that LoB for that WatchList. I need them in the structure this way because the count of how many reports exist within a LoB for a given Watchlist is important elsewhere.
我需要做的是得到一个什么的不同观察列表的列表(基于ID分组),并具有ReportCount在所有的LOB该监视列表的ReportCount的总和。我不能完全得到嵌套的选择逻辑工作的权利。
What I need to do is get a list of the distinct WatchLists (grouped based on ID) and have the ReportCount be the SUM of that watchlist's ReportCount across all LoBs. I can't quite get the nested select logic to work right.
推荐答案
扁平化层次结构的技术是使用的SelectMany
方法。你需要的东西是这样的:
The technique to flatten a hierarchical structure is to use the SelectMany
method. You need something like this:
var result = mainList.SelectMany(x => x.LineOfBusinessList)
.SelectMany(lob => lob.Watchlists)
.GroupBy(wl => wl.ID)
.Select(g => new {
WatchlistID = g.Key,
WatchlistName = g.First().Name,
ReportCount = g.Sum(item => item.ReportCount)
});
第一个的SelectMany
通话将改造原有的列表中的所有项目均 LineOfBusiness
的对象序列。第二个的SelectMany
通话将改造 LineOfBusiness
的序列对象包含所有监视列表<序列/ code>反对他们的。然后你将这些
的监视列表中
S按他们 ID
并对其进行了实际的查询。
The first SelectMany
call will transform the original list to sequence of all LineOfBusiness
objects in all items. The second SelectMany
call will transform a sequence of LineOfBusiness
objects to a sequence containing all Watchlist
objects it them. Then you group these Watchlist
s by they ID
and perform the actual query on them.
这篇关于LINQ和嵌套结构中的数据组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!