HomeSearch

C# Enumerable.Range, Repeat and Empty

Use the Range method on the Enumerable type to get a range of numbers. Invoke Repeat and Empty.
Enumerable.Range. A sequence of numbers progresses in order: 10, 11, 12, 13. With Enumerable.Range, each number is one greater than the previous.IEnumerableLINQ
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.

C# program that uses Enumerable.Range 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); } } } Output 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.
C# program that causes exception using System.Linq; class Program { static void Main() { // This will cause an exception. var numbersNegative = Enumerable.Range(10, -1); } } Output 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.

C# program that uses Enumerable.Repeat method 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); } } } Output 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.

Generic: 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
C# program that uses Enumerable.Empty 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); } } Output 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.

ReadLine: We accept the user input as a string from ReadLine. We then invoke int.TryParse to convert the string to an int.

Console.ReadLineint.Parse

Sum: We call the Sum() extension method on the IEnumerable returned by Enumerable.Range.

Sum
C# program that uses Range, Sum extension 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); } } } } Output 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.

ToArray: We generate new int arrays with ToArray. The example fills 2 Windows Forms menus with the numbers between 0 and 14 inclusive.

Int ArrayToArray

Note: The programming term for notation that expresses an entire list at once is list comprehension.

C# program that uses Enumerable.Range, Windows Forms public partial class ReporterWindow : Form { public ReporterWindow() { // // Autogenerated code. // 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.

Note: Thanks to Nathan Brink for some tips on improving this article. A description of arguments was added.

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.StaticGeneric Class, Method

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.Initialize Array
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.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls