问题
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