LINQ Range

Summary: in this tutorial, you will learn how to use the LINQ Range() method to generate a sequence of integers within a specified range.

Introduction to the LINQ Range() method

The LINQ Range() method allows you to generate a sequence of integers within a range. Here’s the syntax of the Range() method:

IEnumerable<int> Range (int start, int count);Code language: C# (cs)

In this syntax:

  • start represents the first integer in the sequence.
  • count is the number of sequential integers to generate.

The Range() returns an IEnumerable<T> that contains a range of integer numbers.

The method throws an ArgumentOutOfRangeException if the count is less than 0 or start + count - 1 is larger than Int32.MaxValue.

LINQ Range() method examples

Let’s take some examples of using the LINQ Range() method.

1) Using the LINQ Range() method to generate a sequence of integers

The following example uses the Range() method to generate a sequence of 5 integers starting from 0:

using static System.Console;

var numbers = Enumerable.Range(0, 5);
foreach (var number in numbers)
{
    WriteLine(number);
}Code language: C# (cs)

Output:

0
1
2
3
4Code language: C# (cs)

2) Using the LINQ Range() method with the Select() method

The following example uses the Range() method with the Select() method to generate even numbers from 0 to 10:

using static System.Console;

var numbers = Enumerable.Range(0, 6)
                        .Select(x => x*2);

foreach (var number in numbers)
{
    WriteLine(number);
}Code language: C# (cs)

Output:

0
2
4
6
8
10Code language: C# (cs)

In this example, the Range() method first generates a sequence of 6 integers from 0 to 5. And then the Select() method returns a sequence that contains the square of each number in the original sequence.

Summary

  • Use the LINQ Range() method to generate a sequence of integers within a specified range.
Was this tutorial helpful ?