How to select top records using a LINQ query

Introduction


In order to select top records from a list of entities with LINQ, we use the Take method.

Take


The Take method allows you to select a specified number of elements from a list. The number of elements to select is passed as a parameter of the method.

Examples


Simple usage

List<int> list = new List<int> { 23, 18, 7, 91, 115, 102, 33, -88, 77, -6, 12, 4000};

List<int> values = list.Take(3).ToList();  // { 23, 18, 7 }

Note: we use the ToList method in order to avoid the following casting error:

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<int>' to 'System.Collections.Generic.List<int>'. An explicit conversion exists (are you missing a cast?)

Usage in Conjunction with the Where method

List<int> list = new List<int> { 23, 18, 7, 91, 115, 102, 33, -88, 77, -6, 12, 4000};

List<int> values = list.Where(l => l > 20).Take(3).ToList();  // { 23, 91, 115 }

If the parameter passed into the Take method is greater than the actual size of the list, the result will be limited to the size of the list.

List<int> list = new List<int> { 23, 18, 7, 91, 115, 102, 33, -88, 77, -6, 12, 4000};

List<int> values = list.Where(l => l < 0).Take(1000).ToList();  // { -88, -6 }

Advanced usage

Besides using primitive types with the Take 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 = "Jack Nickelson", Age = 17},
    new Student{ FullName = "Lynwood Tsai", Age = 14},
    new Student{ FullName = "Catarina Riviera", Age = 23},
    new Student{ FullName = "Jacquiline Kidder", Age = 19},
    new Student{ FullName = "Francisco Gries", Age = 12},
    new Student{ FullName = "Leida Hills", Age = 15},
    new Student{ FullName = "Kris Harter", Age = 16},
    new Student{ FullName = "Lakia Rask", Age = 18}
}; 

List<Student> values = students.Where(s => s.Age < 18).Take(2).ToList();  // { Jack Nickelson, Lynwood Tsai }

Namespace


To use the Take method, you have to include this namespace:

using System.Linq;

See also