c# Linq remove duplicate items and calculate average values

可紊 提交于 2019-12-14 00:09:52

问题


For example I have a list of objects (properties: Name and value)

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

I want the result:

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

How can I do this?

thanks

sorry guys, duplicate is based on item.Name.


回答1:


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)
  }

or

var results = source.GroupBy(c=>c.Name)
                  .Select(c => new (c.Key, c.Average(d=>d.Value)));



回答2:


You could do it using average and group by:

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


来源:https://stackoverflow.com/questions/17289534/c-sharp-linq-remove-duplicate-items-and-calculate-average-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!