例如,我有一个对象列表(属性:名称和值)
我想要结果:
我该怎么做?
答案 0 :(得分:2)
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)));
答案 1 :(得分:0)
您可以使用平均值和分组来执行此操作:
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)
};