Summary: in this tutorial, you will learn how to use the LINQ TakeLast()
method to return a new collection that contains the last N elements from a sequence.
Introduction to the LINQ TakeLast() method
The LINQ TakeLast()
method allows you to take the last count elements from a sequence:
IEnumerable<TSource> TakeLast<TSource> (
this IEnumerable<TSource> source,
int count
);
Code language: C# (cs)
In this syntax:
source
is the input sequence.count
is the number of elements to take from the end of the sequence.
The TakeLast()
method returns a new enumerable collection IEnumerable<TSource>
that contains the last count elements from the source sequence.
If you want to take N elements from the beginning of a sequence, you can use the Take() method instead.
LINQ TakeLast() method examples
Let’s take some examples of using the LINQ TakeLast()
method.
1) Using LINQ TakeLast() method to filter numbers
The following example uses the LINQ TakeLast()
method to get the last 3 numbers of an array:
using static System.Console;
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var result = numbers.TakeLast(3);
foreach (var number in result)
{
Console.WriteLine(number);
}
Code language: C# (cs)
Output:
8
9
10
Code language: C# (cs)
2) Using LINQ TakeLast() method to filter strings
The following example illustrates how to use the TakeLast()
method to get the last two elements in an array of strings:
using static System.Console;
string[] names = { "Alice", "Bob", "Charlie", "David", "Eve" };
var result = names.TakeLast(2);
foreach (var name in result)
{
WriteLine(name);
}
Code language: C# (cs)
Output:
David
Eve
Code language: C# (cs)
3) Using LINQ TakeLast() method to filter objects
The following example uses the LINQ TakeLast()
method to get the last 3 objects from a list of objects:
using static System.Console;
namespace LINQDemo;
public class Person
{
public required string Name
{
get; set;
}
public int Age
{
get; set;
}
}
public class Program
{
public static void Main(string[] args)
{
var people = new List<Person>
{
new Person { Name = "Alice", Age = 25 },
new Person { Name = "Bob", Age = 26 },
new Person { Name = "Charlie", Age = 30 },
new Person { Name = "William", Age = 22 },
new Person { Name = "Eve", Age = 18 }
};
var result = people.TakeLast(3);
foreach (var person in result)
{
WriteLine($"Name: {person.Name}, Age: {person.Age}");
}
}
}
Code language: C# (cs)
Summary
- Use the LINQ
TakeLast()
method to get the last count elements from a sequence.