C# Program to return specified number of elements from the end of an array

The TakeLast() method in C# returns a specified number of elements from the end of a sequence. It's part of the LINQ library and provides an efficient way to extract the last few elements from arrays, lists, or other enumerable collections.

Syntax

Following is the syntax for using TakeLast()

IEnumerable<T> TakeLast(int count)

Parameters

  • count − The number of elements to return from the end of the sequence.

Return Value

Returns an IEnumerable<T> containing the specified number of elements from the end of the source sequence.

Using TakeLast() with Arrays

Let us first declare and initialize an array and get the last three elements −

using System;
using System.Linq;
using System.Collections.Generic;

public class Demo {
   public static void Main() {
      int[] prod = { 110, 290, 340, 540, 456, 698, 765, 789};
      
      // Get last three elements
      IEnumerable<int> units = prod.TakeLast(3);
      
      Console.WriteLine("Last 3 elements:");
      foreach (int res in units) {
         Console.WriteLine(res);
      }
   }
}

The output of the above code is −

Last 3 elements:
698
765
789

Using TakeLast() with Lists

The TakeLast() method also works with lists and other collections −

using System;
using System.Linq;
using System.Collections.Generic;

public class ListExample {
   public static void Main() {
      List<string> fruits = new List<string> {
         "Apple", "Banana", "Cherry", "Date", "Elderberry", "Fig"
      };
      
      // Get last 2 fruits
      var lastFruits = fruits.TakeLast(2);
      
      Console.WriteLine("Last 2 fruits:");
      foreach (string fruit in lastFruits) {
         Console.WriteLine(fruit);
      }
   }
}

The output of the above code is −

Last 2 fruits:
Elderberry
Fig

Handling Edge Cases

When the requested count is greater than the sequence length, TakeLast() returns all elements −

using System;
using System.Linq;

public class EdgeCaseExample {
   public static void Main() {
      int[] numbers = { 10, 20, 30 };
      
      // Request more elements than available
      var result = numbers.TakeLast(5);
      
      Console.WriteLine("Requesting 5 elements from array of 3:");
      foreach (int num in result) {
         Console.WriteLine(num);
      }
      
      Console.WriteLine($"Total elements returned: {result.Count()}");
   }
}

The output of the above code is −

Requesting 5 elements from array of 3:
10
20
30
Total elements returned: 3

Conclusion

The TakeLast() method provides a simple and efficient way to extract a specified number of elements from the end of any enumerable sequence. It handles edge cases gracefully by returning all available elements when the requested count exceeds the sequence length.

Updated on: 2026-03-17T07:04:35+05:30

268 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements