LINQ和group by数据嵌套在一个结构中

Par*_*ots 3 c# linq nested

我的结构大致如下:

List<ProductLine> -> ID
                     Name
                     ...
                     List<LineOfBusiness> -> ID
                                             Name
                                             ...
                                             List<Watchlist> -> ID
                                                                Name
                                                                ReportCount
Run Code Online (Sandbox Code Playgroud)

监视列表可以存在于多个LoB下,但ReportCount仅用于该监视列表的该LoB下存在的报告计数.我在结构中需要它们,因为对于给定的监视列表,LoB中存在的报告数量在其他地方很重要.

我需要做的是获取不同的WatchLists列表(根据ID分组),并使ReportCount成为所有LoB中该监视列表的ReportCount的SUM.我无法让嵌套的选择逻辑正常工作.

Meh*_*ari 8

展平分层结构的技术是使用该SelectMany方法.你需要这样的东西:

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)  
                     });
Run Code Online (Sandbox Code Playgroud)

第一个SelectMany调用将原始列表转换为LineOfBusiness所有项目中所有对象的序列.第二个SelectMany调用将一系列LineOfBusiness对象转换为包含Watchlist它们所有对象的序列.然后,您将Watchlist它们分组,ID并对它们执行实际查询.