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 传递给函数的用法
Say I have several ObservableCollections 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
该函数将是这样的(未经测试):
您可以使用 LINQ
取而代之的是 Average
方法:The function would be something like this (untested):
You could use the LINQ
Average
method instead:我会完全取消该功能,只使用:
编辑:
将返回和强制转换添加到 int(Average 返回 double)。
I'd do away with the function altogether and just use:
Edit:
Added the return and the cast to an int (Average returns a double).
您可以这样做:
作为替代方案,请考虑使用 LINQ,它已经提供了类似的东西。
You could do something like this:
As an alternative, consider using LINQ, it already provides something like this.
为什么不使用 LINQ 来实现这个目的呢?
Why not use LINQ for this?