Home
Map
Enumerable.Range, Repeat and EmptyUse the Range method on the Enumerable type to get a range of numbers. Invoke Repeat and Empty.
C#
This page was last reviewed on Mar 21, 2023.
Enumerable.Range. A sequence of numbers progresses in order: 10, 11, 12, 13. With Enumerable.Range, each number is one greater than the previous.
IEnumerable
Shows a method
Similar to Range, we can invoke Enumerable.Repeat and Enumerable.Empty. Repeat duplicates a value many times. Empty(), meanwhile, returns no values.
Range example. Let us begin. We invoke Enumerable.Range (part of the System.Linq namespace). We use foreach to loop over all the numbers in the resulting sequence.
foreach
Argument 1 This is the start index. It can be negative or positive. Here we start at the int 5.
Argument 2 This is the count of elements to appear in the final sequence (not a last index). We specify 3 to have 3 elements.
Shows a method
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { // Generate a range of number starting at 5. // ... First parameter is the start number. // Second parameter is the count of numbers (not the last index). IEnumerable<int> numbers = Enumerable.Range(5, 3); foreach (int n in numbers) { Console.WriteLine(n); } } }
5 6 7
Count error. The second argument to Enumerable.Range must be 0 or greater. Here we get an error when we try to create a sequence of negative 1 length.
using System.Linq; class Program { static void Main() { // This will cause an exception. var numbersNegative = Enumerable.Range(10, -1); } }
Unhandled Exception: System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. Parameter name: count at System.Linq.Enumerable.Range(Int32 start, Int32 count) at Program.Main()...
Repeat example. This returns a collection with repeated elements. Enumerable.Repeat is located in the System.Linq namespace. Please add the "using" directive at the top of the program.
Argument 1 This argument to Repeat() is the value that will be repeated in the collection returned by the method.
Argument 2 This is the value that is repeated in the returned IEnumerable collection.
So This means that Enumerable.Repeat(1, 10) will yield ten ones in a sequence. We get an IEnumerable of the type specified.
using System; using System.Linq; class Program { static void Main() { // Create sequence of 10 ones. var integers = Enumerable.Repeat(1, 10); // Display. foreach (int value in integers) { Console.WriteLine("REPEAT: {0}", value); } } }
REPEAT: 1 REPEAT: 1 REPEAT: 1 REPEAT: 1 REPEAT: 1 REPEAT: 1 REPEAT: 1 REPEAT: 1 REPEAT: 1 REPEAT: 1
Empty example. Enumerable.Empty generates an IEnumerable of zero elements. It can be used when you want to avoid a query expression and instead just want to use an empty sequence.
Detail Empty is a static generic method. We must specify the type of the sequence we want to generate.
Here Enumerable.Empty(int) will return a zero-element sequence of ints (IEnumerable(int)).
int, uint
So The Count() extension indicates the sequence is empty. If you use ToArray, you will get an empty array.
Count
using System; using System.Linq; class Program { static void Main() { var empty = Enumerable.Empty<int>(); Console.WriteLine(empty.Count()); int[] array = empty.ToArray(); Console.WriteLine(array.Length); } }
0 0
Combine methods. A benefit of Enumerable.Range, Repeat (and even Empty) is that we can combine them with other extension methods. Here we want to sum numbers up to a certain value.
Start We accept the user input as a string from ReadLine. We then invoke int.TryParse to convert the string to an int.
Console.ReadLine
int.Parse
Next We call the Sum() extension method on the IEnumerable returned by Enumerable.Range.
Sum
using System; using System.Linq; class Program { static void Main() { while (true) { // Get user input. Console.WriteLine("SUM UP TO:"); string result = Console.ReadLine(); // Parse number. if (int.TryParse(result, out int number)) { // Call Sum() on Enumerable.Range. int sum = Enumerable.Range(0, number + 1).Sum(); Console.WriteLine("RESULT: {0}", sum); } } } }
SUM UP TO: 3 RESULT: 6 SUM UP TO: 4 RESULT: 10 SUM UP TO: 100 RESULT: 5050 SUM UP TO:
Windows Forms example. This code is a little different. We use a call to Enumerable.Range to create a control's contents in Windows Forms.
Tip With Enumerable.Range, we can simplify numeric lists and controls in Windows Forms programs.
Detail We generate new int arrays with ToArray. The example fills 2 Windows Forms menus with the numbers between 0 and 14 inclusive.
int Array
ToArray
Note The programming term for notation that expresses an entire list at once is list comprehension.
public partial class ReporterWindow : Form { public ReporterWindow() { InitializeComponent(); // // Add "using System.Linq;" at the top of your source code. // ... Use an array from Enumerable.Range. // ... Set it to the data source of the DropDown boxes. // xComboBox.DataSource = Enumerable.Range(0, 15).ToArray(); yComboBox.DataSource = Enumerable.Range(0, 15).ToArray(); } }
Range, notes. The Range method, with ToArray, returns the entire array needed. This may be easier to read. Expressions encapsulate logic into a single statement.
Info A Range can be used with other LINQ methods and query expressions—these methods are designed to work together.
Empty, implementation. Empty() uses a static generic type and then calls a property (Instance) on that type. An empty array is lazily initialized in the Instance property.
static
Generic
Tip Because Enumerable.Empty caches the zero-element array, it can provide a slight performance advantage.
Convert, notes. We can convert the IEnumerable result from these methods to an array or List. Please use the ToArray or ToList extension methods and assign the result.
ToList
A warning. Using the Enumerable.Range method will have performance negatives over iterative approaches due to the overhead of LINQ. These negatives must be considered.
Array Initialize
With Repeat and Empty, we can get IEnumerables in the same way as Range, but with different values. These methods can be used with queries to help improve program clarity.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Mar 21, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.