C#如何编写可用作GetAverageAge(students,s => s.age)的函数体

| 说我有几个不同类的ObservableCollections:
    public class Employee
    {
        public int age { get; set; }
    }

    public class Student
    {
        public int age { get; set; }
    }

ObservableCollection<Employee> employees = ...;
ObservableCollection<Student> students = ...;
现在,我需要一个函数来计算这些集合的平均年龄:
int employeeAveAge = GetAverageAge(employees, e => e.age);
int studentAveAge = GetAverageAge(students, s => s.age);
如何编写函数体?我不熟悉Action / Fun委托,有人建议我传递一个lambda作为函数的参数 好吧,我不使用内置的LINQ Average(),因为我想学习将lambda传递给函数的用法
已邀请:
该函数将是这样的(未测试):
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;
}
您可以改用LINQ
Average
方法:
public int GetAverageAge<T>(IEnumerable<T> list, Func<T,int> ageFunc)
{
    return (int)list.Average(ageFunc);
}
我会完全放弃该功能,而只需使用:
int employeeAge = (int)employees.Average(e => e.age);
int studentAge = (int)students.Average(e => e.age);
编辑: 将返回值和强制类型转换添加到int(平均返回双精度)。
您可以执行以下操作:
    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;
    }
作为替代方案,考虑使用LINQ,它已经提供了类似的功能。
为什么不为此使用LINQ?
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 :)
    }

要回复问题请先登录注册