C# 用C语言对数据进行分组并进行聚合计算
我在一个列表中有类似的内容,其中对象包含Cat、Type和Items 我想做的是计算类型的平均项,生成如下内容:C# 用C语言对数据进行分组并进行聚合计算,c#,.net,C#,.net,我在一个列表中有类似的内容,其中对象包含Cat、Type和Items 我想做的是计算类型的平均项,生成如下内容: Cat | Type | Items -------------------- A | P | 2 A | Q | 4.5 A | R | 2 B | P | 5.5 B | Q | 3 B | R | 5 正如您所看到的,计算了类型的平均项 最好的方法是什么 假设输入是在IEnumerable类
Cat | Type | Items
--------------------
A | P | 2
A | Q | 4.5
A | R | 2
B | P | 5.5
B | Q | 3
B | R | 5
正如您所看到的,计算了类型的平均项
最好的方法是什么 假设输入是在IEnumerable类型的名为list的变量中提供的,该变量包含例如数据库查询结果、列表、数组等,并且Blah是一个具有名为Cat、type和Items的字段或属性的类:
你能在数据结构上写一行吗?元组列表?@vlad:我假设一个对象有三个属性。对不起,是的,对象类型列表有三个属性
Cat | Type | Items
--------------------
A | P | 2
A | Q | 4.5
A | R | 2
B | P | 5.5
B | Q | 3
B | R | 5
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) })
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 );
}
}