Home | Contact Us

CSharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript

C# Enumerable.Range

This C# example program uses the Range method on the Enumerable type. It requires System.Linq.

Enumerable.Range generates a collection.

It can simplify numeric lists and drop-downs in Windows Forms programs. You require a DropDownList containing a range of numbers. We generate new int arrays with Enumerable.Range.

Int Array

Example. Here we replace cumbersome loops or helper methods. This can help rapid development and maintenance. The programming term for notation that expresses an entire list at once is list comprehension.

Next: The example fills two Windows Forms menus with the numbers between 0 and 15. The results are shown in the screenshot.

C# program that uses Enumerable.Range

public partial class ReporterWindow : Form
    public ReporterWindow()
	// Autogenerated code.

	// Add "using System.Linq;" at the top of your source code.
	// Use an array from Enumerable.Range from 0 to 15 and set it
	// to the data source of the DropDown boxes.
	xComboBox.DataSource = Enumerable.Range(0, 15).ToArray();
	yComboBox.DataSource = Enumerable.Range(0, 15).ToArray();

The Range method, with ToArray, returns the entire array needed. This may be easier to scan. The above example creates the arrays in one line of code each. Further, it hoists more of the work to the .NET Framework.



With expression-based programming, we reduce source code size. Expressions encapsulate logic into a single statement, instead of many procedural commands. They are often clearer and easier to maintain.


Summary. We replaced loops with Enumerable.Range expressions from LINQ. Imagine your project used this code in thousands of places. With expressions, your final code could have 10,000 lines instead of 80,000 statements.

However: Using the Enumerable.Range method will have performance negatives over iterative approaches due to the overhead of LINQ.

Initialize Array