2013-06-26 107 views
0

我想知道如何解決我的問題與Linq按月份聚合計數。林奇集團按月份,總計數

下面是我的樣本數據:

Code  CodeName Color  Month 
11111  One  Red   1 
11111  One  Red   1 
11111  One  Red   2 
22222  Two  Green  2 
33333  Three  Yellow  3 
44444  Four  Blue   4 
44444  Four  Blue   4 
55555  Five  White  5 

我想看到的結果是這樣的:

Code  CodeName  Color  Count(Mont1) Month2  Month3 Month4 Month5 
11111  one  red   2   1   0   0   0 
22222  two  Green   0   1   0   0   0 
33333  three  Yellow  0   0   1   0   0 
44444  four  Blue   0   0   0   2   0 
55555  five  White   0   0   0   0   1 
+3

那麼你到目前爲止嘗試過什麼? – Deeko

+0

尋找LINQ +支點並找出沒有銀彈。之前已經有很多方面提出過這個問題。 –

回答

0

這裏是產生你想要的結果

它的核心的例子是這樣的:

  • 組中的元素可以通過Code性質
  • 組中的每個分組中的元素可以通過Color性質
  • 過程中的每個分組,產生其中每個MonthX屬性被設置到對象的內分組內的計數的結果(項目由碼通過顏色)具有給定的月份標識符

這特別處理問題中提供的5個月值,您可以將您喜歡的所有月份值拆分爲您自己的結果對象上的屬性,或者將其構建到如果需要其他值,則爲月份索引與計數字典。

public enum Number 
{ 
    One = 11111, 
    Two = 22222, 
    Three = 33333, 
    Four = 44444, 
    Five = 55555 
} 

public class Data 
{ 
    public Number Code { get; set; } 
    public string CodeName { get { return Enum.GetName(typeof(Number), Code); } } 
    public ConsoleColor Color { get; set; } 
    public int Month { get; set; } 
} 

public class Result 
{ 
    public Number Code { get; set; } 
    public string CodeName { get { return Enum.GetName(typeof(Number), Code); } } 
    public ConsoleColor Color { get; set; } 
    public int Month1 { get; set; } 
    public int Month2 { get; set; } 
    public int Month3 { get; set; } 
    public int Month4 { get; set; } 
    public int Month5 { get; set; } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     var items = new Data[] 
     { 
      new Data{Code = Number.One, Color = ConsoleColor.Red, Month = 1}, 
      new Data{Code = Number.One, Color = ConsoleColor.Red, Month = 1}, 
      new Data{Code = Number.One, Color = ConsoleColor.Red, Month = 2}, 
      new Data{Code = Number.Two, Color = ConsoleColor.Green, Month = 2}, 
      new Data{Code = Number.Three, Color = ConsoleColor.Yellow, Month = 3}, 
      new Data{Code = Number.Four, Color = ConsoleColor.Blue, Month = 4}, 
      new Data{Code = Number.Four, Color = ConsoleColor.Blue, Month = 4}, 
      new Data{Code = Number.Five, Color = ConsoleColor.White, Month = 5}, 
     }; 

     var results = items.GroupBy(x => x.Code).Select(
      x => x.GroupBy(y => y.Color) 
        .Select(z => new Result 
        { 
         Code = x.Key, 
         Color = z.Key, 
         Month1 = z.Count(q => q.Month == 1), 
         Month2 = z.Count(q => q.Month == 2), 
         Month3 = z.Count(q => q.Month == 3), 
         Month4 = z.Count(q => q.Month == 4), 
         Month5 = z.Count(q => q.Month == 5), 
        }).ToList()); 

     var resultList = results.ToList(); 
    } 
}