16

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});
    }
}
Drag and Drop
  • 2,672
  • 3
  • 25
  • 37
Nihau
  • 306
  • 1
  • 1
  • 8

3 Answers3

33

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

using System.Linq;

list.Average(item => item.a);
dcastro
  • 66,540
  • 21
  • 145
  • 155
  • @D Stanley, why Select() is not good in this case? any disadvantage in terms of performance? – Sheen Jun 24 '14 at 13:06
  • @Sheen Although in most cases it won't be noticeable, there is a slight perf hit because you've added another enumerator on top of average's enumerator. That's an extra level of indirection. But the main problem is: you don't need it. Calling methods that you don't need hinders readability and increases complexity at best. If you had a big chain of linq method calls, adding needless `Selects` in between would make your eyes bleed. – dcastro Jun 24 '14 at 13:19
5

You could try this one:

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

where ListOfA is a List of objects of type A.

Christos
  • 53,228
  • 8
  • 76
  • 108
3

You can use Enumerable.Average

var average = L.Select(r => r.a).Average();
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396