Return Specified Number of Elements from the End of an Array in C#



Use the TakeLast() method to return elements from the end of an array.

Let us first declare and initialize an array.

int[] prod = { 110, 290, 340, 540, 456, 698, 765, 789};

Now, let’s get the last three elements.

IEnumerable<int> units = prod.AsQueryable().TakeLast(3);

Let us see the complete code.

Example

 Live Demo

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};
      // value of last three products
      IEnumerable<int> units = prod.AsQueryable().TakeLast(3);
      foreach (int res in units) {
         Console.WriteLine(res);
      }
   }
}

Output

698
765
789
Updated on: 2020-06-23T07:28:31+05:30

161 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements