例如我有一个对象列表(属性:名称和值)
- 第 1 项 20;
- 项目2 30;
- 第 1 项 50;
我想要结果:
- 项目 1 35 (20+50)/2
- 项目 2 30
我怎样才能做到这一点?
对不起,伙计们,重复是基于item.Name
.
var results =
from kvp in source
group kvp by kvp.Key.ToUpper() into g
select new
{
Key= g.Key,
Value= g.Average(kvp => kvp.Value)
}
或者
var results = source.GroupBy(c=>c.Name)
.Select(c => new (c.Key, c.Average(d=>d.Value)));
您可以使用平均值和分组来做到这一点:
public class myObject
{
public string Name {get;set;}
public double Value {get;set;}
}
var testData = new List<myObject>() {
new myObject() { Name = "item1", Value = 20 },
new myObject() { Name = "item2", Value = 30 },
new myObject() { Name = "item1", Value = 50 }
};
var result = from x in testData
group x by x.Name into grp
select new myObject() {
Name=grp.Key,
Value= grp.Average(obj => obj.Value)
};