如何解决C#如何编写可用作GetAverageAgestudents,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;
}
您可以改用LINQAverage
方法:
public int GetAverageAge<T>(IEnumerable<T> list,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,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 :)
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。