2009-07-21 56 views
7

我有记录的结构如下列表:(!简单的例子)LINQ中的多级分组?

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

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

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语句会是什么呢?

+0

你可以提供输入速率的列表,所期望的输出? – 2009-07-21 13:56:00

+0

所需的输出是RateList类型的单个对象。 InterestFrom/InterestTo和IncomeFrom/IncomeTo为每个代码重复值。示例记录为:(“AB”,0,6,10000,20000,40.3)或(“AB”,6,7.5,10000,20000,40.3)。 – 2009-07-21 14:06:09

回答

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