Average 扩展方法计算集合中数值项的平均值。Average 方法返回可空或不可空的十进制值、双值或浮点值。
下面的示例演示Agerage方法,该方法返回集合中所有整数的平均值。
IList<int> intList = new List<int>>() { 10, 20, 30 }; var avg = intList.Average(); Console.WriteLine("Average: {0}", avg);
您可以将类的 int、 decimal、 double 或 float 属性指定为 lambda 表达式,希望获得其平均值。下面的示例演示复杂类型上的 Average 方法。
IList<Student> studentList = new List<Student>>() { new Student() { StudentID = 1, StudentName = "John", Age = 13} , new Student() { StudentID = 2, StudentName = "Moin", Age = 21 } , new Student() { StudentID = 3, StudentName = "Bill", Age = 18 } , new Student() { StudentID = 4, StudentName = "Ram" , Age = 20} , new Student() { StudentID = 5, StudentName = "Ron" , Age = 15 } }; var avgAge = studentList.Average(s => s.Age); Console.WriteLine("Average Age of Student: {0}", avgAge);
Dim studentList = New List(Of Student) From { New Student() With {.StudentID = 1, .StudentName = "John", .Age = 13}, New Student() With {.StudentID = 2, .StudentName = "Moin", .Age = 21}, New Student() With {.StudentID = 3, .StudentName = "Bill", .Age = 18}, New Student() With {.StudentID = 4, .StudentName = "Ram", .Age = 20}, New Student() With {.StudentID = 5, .StudentName = "Ron", .Age = 15} } Dim avgAge = studentList.Average(Function(s) s.Age) Console.WriteLine("学生的平均年龄: {0}", avgAge)
学生的平均年龄:17.4
C # 不支持查询语法中的 Average 运算符。但是,VB.Net 支持它,如下所示。
Dim studentList = New List(Of Student) From { New Student() With {.StudentID = 1, .StudentName = "John", .Age = 13}, New Student() With {.StudentID = 2, .StudentName = "Moin", .Age = 21}, New Student() With {.StudentID = 3, .StudentName = "Bill", .Age = 18}, New Student() With {.StudentID = 4, .StudentName = "Ram", .Age = 20}, New Student() With {.StudentID = 5, .StudentName = "Ron", .Age = 15} } Dim avgAge = Aggregate st In studentList Into Average(st.Age) Console.WriteLine("学生的平均年龄: {0}", avgAge)
学生的平均年龄:17.4
了解另一个聚合运算符-下一节中的Count。