Count运算符返回集合中的元素数或满足给定条件的元素数。
Count()扩展方法有以下两种重载:
Count() 重载:
int Count<TSource>();int Count<TSource>(Func<TSource, bool> predicate);
Count的第一个重载方法返回指定集合中的元素数,而第二个重载方法返回满足指定条件的元素数(由lambda表达式/predicate 谓词函数给出)。
下面的示例演示了原语集合上的Count()。
IList<int> intList = new List<int>() { 10, 21, 30, 45, 50 }; var totalElements = intList.Count(); Console.WriteLine("元素总数: {0}", totalElements); var evenElements = intList.Count(i => i%2 == 0); Console.WriteLine("偶数元素: {0}", evenElements);
元素总数:5 偶数元素:3
下面的示例演示Count()复杂类型集合上的方法。
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 = "Mathew" , Age = 15 } }; var totalStudents = studentList.Count(); Console.WriteLine("学生总人数: {0}", totalStudents); var adultStudents = studentList.Count(s => s.Age >= 18); Console.WriteLine("成人学生人数: {0}", adultStudents );
学生总人数:5 成人学生人数:3
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 totalStudents = studentList.Count() Console.WriteLine("学生总人数: {0}", totalStudents)
学生总人数:5
在VB.Net中不支持带有谓词参数的Count(predicate)扩展方法。
// 学生集合 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 totalStudents = Aggregate st In studentList Into Count(st.Age >= 18) Console.WriteLine("学生总人数: {0}", totalStudents)
学生总人数:3
C#查询语法不支持聚合运算符。但是,您可以将查询括在方括号中并使用聚合函数,如下所示。
var totalAge = (from s in studentList select s.age).Count();
在下一部分中了解另一个聚合运算符-Max。