LINQ中的多级分组?

时间:2009-07-21 13:36:58

标签: c# linq

我有一个具有以下结构的记录列表:(简化示例!)

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

是的,我有一个List< Rate>定义。我需要将此列表转换为以下简化结构:

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

我想用一个LINQ查询来做这件事。我可以解决其他解决方案,但挑战是在一个LINQ语句中完成。 基本上,顶级组按代码分组。下一个级别是值InterestFrom和InterestTo,最低级别是IncomeFrom,IncomeTo和Value的列表。

那么,LINQ语句会是什么呢?

1 个答案:

答案 0 :(得分:18)

这是非常巨大的,但这就是我所拥有的:

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