2009-07-21 82 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() 
       };