Introduction
In order to get the number of rows selected with LINQ, we use the Count method.
Count
The Count method allows you to count the number of elements in a list.
Examples
Simple usage
List<int> list = new List<int> { 55, 301, 14, 13, 1, 77, 17, 33};
int count = list.Count(); // 8
Usage in Conjunction with the Where method
List<int> list = new List<int> { 23, 18, 7, 91, 115, 102, 33, -88, 77, -6, 12};
int count = list.Where(l => l > 100).Count(); // 2
Advanced usage
Besides using primitive types with the Count method, we can also use reference types.
public class Student {
public string FullName { get; set; }
public int Age { get; set; }
}
List<Student> students = new List<Student> {
new Student{ FullName = "Emilio Maxwell", Age = 23},
new Student{ FullName = "Shannon Vaughn", Age = 14},
new Student{ FullName = "Emilio Maxwell", Age = 17},
new Student{ FullName = "Alma Cunningham", Age = 15},
new Student{ FullName = "Gilberto Christensen", Age = 20},
new Student{ FullName = "Emmett Banks", Age = 19},
new Student{ FullName = "Robyn May", Age = 16},
new Student{ FullName = "Candice Thompson", Age = 13}
};
/* Number of adult students */
int count = students.Where(l => l.Age > 18).Count(); // 3
Note: Instead of using the Where method, we can also specify our conditions inside the Count method and the result will be the same.
/* Number of adult students */
int count = students.Count(l => l.Age > 18); // 3
Namespace
To use the Count method, you have to include this namespace:
using System.Linq;