Enumerable.Range() / Repeat() / Empty()
Static LINQ methods for generating sequences. They let you easily create ranges, repeated values, and empty sequences.
Syntax
using System.Linq; // Generates a sequence of count consecutive integers starting from start. IEnumerable<int> range = Enumerable.Range(start, count); // Generates a sequence that repeats element count times. IEnumerable<T> repeated = Enumerable.Repeat(element, count); // Generates an empty sequence with zero elements. IEnumerable<T> empty = Enumerable.Empty<T>();
Method List
| Method | Description |
|---|---|
| Enumerable.Range(start, count) | Returns a sequence of count consecutive integers starting from start. |
| Enumerable.Repeat(element, count) | Returns a sequence that repeats the specified element count times. |
| Enumerable.Empty<T>() | Returns an empty sequence with zero elements. Use this when you need an empty enumerable of a specific type. |
Sample Code
using System;
using System.Collections.Generic;
using System.Linq;
// Generates a sequence from 1 to 10.
IEnumerable<int> range = Enumerable.Range(1, 10);
Console.WriteLine(string.Join(", ", range)); // 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
// Gets only even numbers from 0 to 9 (combining Range and Where).
IEnumerable<int> evens = Enumerable.Range(0, 10).Where(n => n % 2 == 0);
Console.WriteLine(string.Join(", ", evens)); // 0, 2, 4, 6, 8
// Uses Range + Select to generate powers of 2.
IEnumerable<int> powers = Enumerable.Range(0, 8).Select(n => (int)Math.Pow(2, n));
Console.WriteLine(string.Join(", ", powers)); // 1, 2, 4, 8, 16, 32, 64, 128
// Repeat: repeats the same value 5 times.
IEnumerable<string> hellos = Enumerable.Repeat("Hello", 5);
Console.WriteLine(string.Join(", ", hellos)); // Hello, Hello, Hello, Hello, Hello
// Repeat: creates a list initialized with 0.
List<int> zeros = Enumerable.Repeat(0, 10).ToList();
Console.WriteLine(zeros.Count); // 10
// Empty: returns an empty sequence of the specified type (can be used instead of null).
IEnumerable<string> empty = Enumerable.Empty<string>();
Console.WriteLine(empty.Any()); // false
// Example of returning an empty sequence as a method's return value.
IEnumerable<int> GetNumbers(bool flag) =>
flag ? Enumerable.Range(1, 5) : Enumerable.Empty<int>();
Console.WriteLine(string.Join(", ", GetNumbers(true))); // 1, 2, 3, 4, 5
Console.WriteLine(string.Join(", ", GetNumbers(false))); // (empty)
Notes
'Enumerable.Range()' uses deferred execution, so generating a large range does not consume memory all at once. Calling 'ToList()' to materialize the sequence, however, loads all elements into memory.
The second argument of 'Enumerable.Range()' is the count of elements, not the end value. For example, to generate 1 through 10, write 'Range(1, 10)' — not 'Range(1, 11)'.
The generated sequence can be combined with other LINQ methods. See 'Enumerable.Select()' for transformations and 'Enumerable.Where()' for filtering.
If you find any errors or copyright issues, please contact us.