问题
I have list of A, and I want to count average on it's field a.
What's the best way to do it?
class A
{
int a;
int b;
}
void f()
{
var L = new List<A>();
for (int i=0; i<3; i++)
{
L.Add(new A(){a = i});
}
}
回答1:
Enumerable.Average has an overload that takes a Func<T, int>
as an argument.
using System.Linq;
list.Average(item => item.a);
回答2:
You could try this one:
var average = ListOfA.Select(x=>x.a).Average();
where ListOfA
is a List of objects of type A
.
回答3:
You can use Enumerable.Average
var average = L.Select(r => r.a).Average();
来源:https://stackoverflow.com/questions/24386928/counting-average-on-listt-field