c#Linq删除重复项并计算平均值

时间:2013-06-25 05:08:13

标签: c# linq group-by

例如,我有一个对象列表(属性:名称和值)

  • item1 20;
  • item2 30;
  • item1 50;

我想要结果:

  • item1 35(20 + 50)/ 2
  • item2 30

我该怎么做?

感谢

抱歉,重复是基于item.Name。

2 个答案:

答案 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)
                                    };