2013-06-26 105 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(); 
    } 
}