Problem. You want to simplify numeric lists and drop downs in Windows Forms programs. You require a DropDownList containing all numbers between a maximum and minimum query. Solution. Here we generate new arrays with Enumerable.Range in LINQ, using the C# programming language.
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. The example fills two windows forms menus with the numbers between 0 and 15.
~~~ Program that uses Enumerable.Range (C#) ~~~
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 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();
}
}Description. It shows list comprehension syntax. The Range method returns the entire arrays we built up programmatically in the first example. This may be easier to scan. The above example creates the arrays in one line of code each. Furthermore, it hoists more of the work to the C# compiler.
Expression-based programming. You replace a lot of code with a little bit of code. Expressions encapsulate logic into a single statement, instead of many procedural commands. Sometimes performance of expressions is no better, but they are often clearer and easier to maintain.
Here we saw a way to replace loops with Enumerable.Range expressions from LINQ, using the C# programming language. 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. Note however that using the Enumerable.Range method will have performance negatives over iterative approaches due to the overhead of LINQ. [C# Initialize Arrays - dotnetperls.com]