Referenced from Here
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;
}
I have a List 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.
Solution:
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()
};