LINQ and the group on data nested in the structure

I have a structure that looks something like this:

List<ProductLine> -> ID
                     Name
                     ...
                     List<LineOfBusiness> -> ID
                                             Name
                                             ...
                                             List<Watchlist> -> ID
                                                                Name
                                                                ReportCount

A watchlist may exist under several LoBs, but a ReportCount will only be for the number of reports that exist in this LoB for this WatchList. I need them in a structure this way because the number of reports in LoB for a given watchlist is important elsewhere.

I need to make a list of individual watchlists (grouped by ID), and ReportCount is the SUM of this ReportCount for all LoBs. I cannot completely make the nested selection logic work correctly.

+3
source share
1 answer

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

SelectMany LineOfBusiness . SelectMany LineOfBusiness , Watchlist. Watchlist ID .

+8

Source: https://habr.com/ru/post/1712043/


All Articles