Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting average on list<T> field

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});
    }
}
like image 672
Nihau Avatar asked Jun 24 '14 12:06

Nihau


People also ask

How do you find the average of a list?

Summary: The formula to calculate average is done by calculating the sum of the numbers in the list divided by the count of numbers in the list.

How do you average a list in C#?

Use the Linq Average() method to find the average of a sequence of numeric values. Firstly, set a sequence. List<int> list = new List<int> { 5, 8, 13, 35, 67 }; Now, use the Queryable Average() method to get the average.

How do you find the mean of a nested list in Python?

Python doesn't have a built-in function to calculate an average of a list, but you can use the sum() and len() functions to calculate an average of a list. In order to do this, you first calculate the sum of a list and then divide it by the length of that list.


1 Answers

Enumerable.Average has an overload that takes a Func<T, int> as an argument.

using System.Linq;

list.Average(item => item.a);
like image 165
dcastro Avatar answered Oct 21 '22 07:10

dcastro