LINQ Range Method

In LINQ, the Range method or operator is useful to generate the sequence of integers or numbers based on specified values of start index and end index. 

Syntax of LINQ Range Method

Following is the syntax of the LINQ Range method to generate a sequence of numbers based on specified index values.

 

C# Code

 

IEnumerable<int> obj = Enumerable.Range(100, 10);

VB.NET Code

 

Dim obj As IEnumerable(Of Integer) = Enumerable.Range(100, 10)

If you observe the above syntax, we defined the Range method with two parameters. Here, the first parameter tells the starting elements of the integer, and the second parameter is the one that tells up to which limit it display the integers in a sequence.

Example of LINQ Range Method

Following is the example of the LINQ Range method to generate a collection that contains a sequence of numbers.

 

C# Code

 

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

namespace Linqtutorials
{
  class Program
  {
    static void Main(string[] args)
    {
      IEnumerable<int> obj = Enumerable.Range(100, 10);
      foreach (var item in obj)
      {
        Console.WriteLine(item);
      }
      Console.ReadLine();
    }
  }
}

VB.NET Code

 

Module Module1
Sub Main()
Dim obj As IEnumerable(Of Integer) = Enumerable.Range(100, 10)
For Each item In obj
Console.WriteLine(item)
Next
Console.ReadLine()
End Sub
End Module

If you observe the above example, we defined Range from (100, 10), so it will take starting number as ”100” and till “109” it will return because here we defined the second parameter as 10, so it will return 10 numbers.

Result of LINQ Range Method Example

Following is the result of the LINQ Range method example.

 

100
101
102
103
104
105
106
107
108
109

This is how we can use the LINQ Range method to generate a collection with a sequence of numbers in c#, vb.net.