Counting average on list<T> field

丶灬走出姿态 提交于 2020-06-27 06:51:30

问题


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

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