Reputation: 89
Lately I ran in this programming problem. I want to reuse this one "Average" method a lot of times, but with different integer properties. I tried surfing through internet, searching for something similar, but I found nothing. So i would like to ask you for a little help. Maybe you could suggest me something more useful or maybe this type of problem solving for this situation is not suited at all?
public double CountAverage(NameOfTheProperty)
{
double Average = 0;
double Amount = 0;
foreach (Athlete athlete in this.Athletes)
{
Amount += athlete.NameOfTheProperty;
}
return Average;
}
Upvotes: 0
Views: 42
Reputation: 156998
Usually this is solved with a function. In your case, there is already a LINQ function to do so (called Average
), but to show you how it works:
public double CountAverage(Func<Athlete, double> func)
{
double Average = 0;
double Amount = 0;
foreach (Athlete athlete in this.Athletes)
{
Amount += func(athlete);
}
return Amount / this.Athletes.Count;
}
You use it like this:
double d = CountAverage(a => a.NameOfProperty);
The LINQ version:
double d = this.Athletes.Average(a => a.NameOfProperty);
Upvotes: 7