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

时间:2011-04-20 06:01:47

标签: c# lambda

假设我有几个不同类的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传递给函数的用法

5 个答案:

答案 0 :(得分:3)

我完全取消了这个功能,只需使用:

int employeeAge = (int)employees.Average(e => e.age);
int studentAge = (int)students.Average(e => e.age);

编辑: 将返回和强制转换添加到int(Average返回一个double)。

答案 1 :(得分:3)

该功能将是这样的(未经测试):

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);
}

答案 2 :(得分:2)

你可以这样做:

    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,它已经提供了类似的内容。

答案 3 :(得分:0)

为什么不为此使用LINQ?

employees.Select(e => e.age).Average()

students.Select(s => s.age).Average()

答案 4 :(得分:0)

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 :)
    }