LINQ and group by data nested within a structure

杀马特。学长 韩版系。学妹 提交于 2019-12-04 11:57:45

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)  
                     });

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 Watchlists by they ID and perform the actual query on them.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!