在C#中对数据进行分组并进行聚合计算

时间:2011-01-13 22:55:06

标签: c# .net

我在List<object> object包含CatTypeItems的内容中有类似内容。

Cat  | Type | Items
--------------------
 A   |  P   |  3
 A   |  Q   |  4
 A   |  R   |  2
 A   |  P   |  1
 A   |  Q   |  5
 B   |  P   |  2
 B   |  Q   |  1
 B   |  R   |  3
 B   |  P   |  9

我想要做的是计算类型的平均项,所以产生这样的东西:

Cat  | Type | Items
--------------------
 A   |  P   |  2
 A   |  Q   |  4.5
 A   |  R   |  2
 B   |  P   |  5.5
 B   |  Q   |  3
 B   |  R   |  5

如您所见,计算了类型的平均项目 什么是最好的方法呢?

2 个答案:

答案 0 :(得分:7)

假设输入是在list类型的IEnumerable<Blah>变量中提供的(例如,包含数据库查询结果,List<Blah>,数组等等。) ,Blah是一个包含名为CatTypeItems的字段或属性的类:

var result = list.GroupBy(entry => new { entry.Cat, entry.Type })
                 .Select(group => new { group.Key.Cat, group.Key.Type,
                                        Items = group.Average(e => e.Items) })

答案 1 :(得分:2)

class  Stuff
{
    public string Cat { get; set; }
    public string Type { get; set; }
    public double Items { get; set; }
}

static void Main( string[] args )
{
    var list = new List<Stuff>();
    list.Add( new Stuff { Cat = "A", Type = "P", Items = 3 } );
    list.Add( new Stuff { Cat = "A", Type = "Q", Items = 4 } );
    list.Add( new Stuff { Cat = "A", Type = "R", Items = 2 } );
    list.Add( new Stuff { Cat = "A", Type = "P", Items = 1 } );
    list.Add( new Stuff { Cat = "A", Type = "Q", Items = 5 } );
    list.Add( new Stuff { Cat = "B", Type = "P", Items = 2 } );
    list.Add( new Stuff { Cat = "B", Type = "Q", Items = 1 } );
    list.Add( new Stuff { Cat = "B", Type = "R", Items = 3 } );
    list.Add( new Stuff { Cat = "B", Type = "P", Items = 9 } );

    var result = from stuff in list
                 group stuff by new { stuff.Cat, stuff.Type } into g
                 select new { Cat = g.Key.Cat,
                              Type = g.Key.Type,
                              AvgItems = g.Average( s => s.Items ) };

    foreach( var s in result )
    {
        Console.WriteLine( "{0}  |  {1}  |  {2}", s.Cat, s.Type, s.AvgItems );
    }
}