C# How to write a function body that could be used as GetAverageAge(students, s => s.age)
Say I have several Observabl开发者_StackOverflow中文版eCollections of different classes:
public class Employee
{
public int age { get; set; }
}
public class Student
{
public int age { get; set; }
}
ObservableCollection<Employee> employees = ...;
ObservableCollection<Student> students = ...;
now I need a function to calculation the average age of these collections:
int employeeAveAge = GetAverageAge(employees, e => e.age);
int studentAveAge = GetAverageAge(students, s => s.age);
How to write the function body? Im not familiar with Action/Fun delegate, and somebody suggested me to pass a lambda as the function's parameter
well I don't use the build-in LINQ Average() because I want to learn the usage of passing lambda to function
The function would be something like this (untested):
public int GetAverageAge<T>(IEnumerable<T> list, Func<T,int> ageFunc)
{
int accum = 0;
int counter = 0;
foreach(T item in list)
{
accum += ageFunc(item);
counter++;
}
return accum/counter;
}
You could use the LINQ Average
method instead:
public int GetAverageAge<T>(IEnumerable<T> list, Func<T,int> ageFunc)
{
return (int)list.Average(ageFunc);
}
I'd do away with the function altogether and just use:
int employeeAge = (int)employees.Average(e => e.age);
int studentAge = (int)students.Average(e => e.age);
Edit: Added the return and the cast to an int (Average returns a double).
You could do something like this:
double GetAverageAge<T>(IEnumerable<T> persons, Func<T, int> propertyAccessor)
{
double acc = 0.0;
int count = 0;
foreach (var person in persons)
{
acc += propertyAccessor(person);
++count;
}
return acc / count;
}
As an alternative, consider using LINQ, it already provides something like this.
Why not use LINQ for this?
employees.Select(e => e.age).Average()
students.Select(s => s.age).Average()
I Would do it this way for a normal list not sure about observable collection :
List<Employee> employees = new List<Employee>
{
new Employee{age = 12},
new Employee{age = 14}};
Func<List<Employee>, int> func2 = (b) => GetAverageAge(b);
private static int GetAverageAge(List<Employee> employees)
{
return employees.Select(employee => employee.age).Average; //Thats quicker i guess :)
}
精彩评论