Get the range of elements in a C# list


Use the GetRange() method to get the range of elements −

Firstly, set a list and add elements −

List<int> arr1 = new List<int>();
arr1.Add(10);
arr1.Add(20);
arr1.Add(30);
arr1.Add(40);
arr1.Add(50);

Now, under a new list get the range of elements between index 1 and 3 −

List<int> myList = arr1.GetRange(1, 3);

Here is the complete code −

Example

 Live Demo

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      List<int> arr1 = new List<int>();
      arr1.Add(10);
      arr1.Add(20);
      arr1.Add(30);
      arr1.Add(40);
      arr1.Add(50);
      Console.WriteLine("Initial List ...");
      foreach (int i in arr1) {
         Console.WriteLine(i);
      }
      Console.WriteLine("Getting elements between a range...");
      List<int> myList = arr1.GetRange(1, 3);
      foreach (int res in myList) {
         Console.WriteLine(res);
      }
   }
}

Output

Initial List ...
10
20
30
40
50
Getting elements between a range...
20
30
40

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 22-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements