Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi-level grouping in LINQ?

Tags:

c#

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?

like image 284
Wim ten Brink Avatar asked Jul 21 '09 13:07

Wim ten Brink


1 Answers

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()
               };
like image 51
Ryan Versaw Avatar answered Sep 23 '22 04:09

Ryan Versaw