The average count value in the <T> list box

For example: I have a list A, and I want to calculate the average field a for it. What is the best way to do this? The stupid solution I found is to create LAverage = new List (), fill it with all La and call LAverage.average ()

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}); } } 
+7
iterator c # average mean
source share
3 answers

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

 using System.Linq; list.Average(item => item.a); 
+19
source share

You can use Enumerable.Average

 var average = L.Select(r => ra).Average(); 
+3
source share

You can try the following:

 var average = ListOfA.Select(x=>xa).Average(); 

where ListOfA is a list of type A objects.

+3
source share

All Articles