结合重复和平均值

时间:2014-07-22 20:54:07

标签: c# linq list lambda

我有一个对象列表,可能包含也可能不包含具有相同属性的对象。如果存在重复项(例如具有相同属性值的对象),我想通过平均它们的值来组合它们。

例如(实际对象可以有超过3个属性):

var myList = List<Attribute>(){
    new Attribute(){Id = "Score", Label = "Score", Rating = 4.5},
    new Attribute(){Id = "Price", Label = "Retail Price", Rating = 14.99},
    new Attribute(){Id = "Score", Label = "Score", Rating = 3.5},
    new Attribute(){Id = "Value", Label = "Overall Value", Rating = 5}
}

我想将两个属性与属性Id =“Score”结合起来,并取两个等级的平均值得到类似的结果:

var myList = List<Attribute>(){
    new Attribute(){Id = "Score", Label = "Score", Rating = 4.0},
    new Attribute(){Id = "Price", Label = "Retail Price", Rating = 14.99},
    new Attribute(){Id = "Value", Label = "Overall Value", Rating = 5}
}

我相信我需要使用GroupBySelectAverage这样的伪代码myList.GroupBy(x => x.Id).Select(x=> new{ x.Id, x.Label, x.Average(x=>x.Rating)} )

有人能指出我正确的方向吗?非常感谢。

1 个答案:

答案 0 :(得分:2)

不确定Label属性是什么,它总是一样吗? Nevertheles,它应该看起来像:

var output = myList.GroupBy(x => x.Id,
                            (key, values) => new Attribute() 
                            {
                               Id = key,
                               Label = values.First().Label,
                               Rating = values.Average(v => v.Rating)
                            })
                    .ToList();