简体   繁体   中英

Multi-level grouping in LINQ?

I have a list of records with the following structure: (Simplified example!)

class Rate
{
    string Code;
    double InterestFrom;
    double InterestTo;
    double IncomeFrom;
    double IncomeTo;
    double Value;
}

And yes, I have a List<Rate> defined. I need to convert this list to the following simplified structure:

class RateList
{
   List<Code> code;
}
class Code
{
    string code;
    List<Interest> interest;
}
class Interest
{
    double InterestFrom;
    double InterestTo;
    List<Income> income;
}
class Income
{
    double IncomeFrom;
    double IncomeTo;
    double Value;
}

And I would like to do this with a single LINQ query. I can work out other solutions but the challenge is to do it within one LINQ statement. Basically, the top-level group is grouped by code. The next level by the values InterestFrom and InterestTo and the lowest level is a list of IncomeFrom, IncomeTo and Value.

So, what would be the LINQ statement for this?

This is pretty huge, but here is what I have:

var rateList = new RateList
               {
                   code = (from r in rates
                           group r by r.Code into g
                           select new Code
                           {
                               code = g.Key,
                               interest = (from i in g
                                           group i by new {i.InterestFrom, i.InterestTo} into g2
                                           select new Interest
                                           {
                                               InterestFrom = g2.Key.InterestFrom,
                                               InterestTo = g2.Key.InterestTo,
                                               income = (from inc in g2
                                                         select new Income
                                                         {
                                                             IncomeFrom = inc.IncomeFrom,
                                                             IncomeTo = inc.IncomeTo,
                                                             Value = inc.Value
                                                         }).ToList()
                                           }).ToList()
                           }).ToList()
               };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM