C#Dot Net Perls

LINQ
Enumerable Range Example

by Sam Allen
Shows the result of Enumerable.Range on a ComboBox.

Problem

Use the Enumerable.Range method to greatly simplify lists and drop downs in Windows Forms programs. Another possible problem is that you may need to have a ComboBox with numbers for positions on a game board. You may need to have a DropDownList with all numbers between a MAX and MIN SQL query, or the day numbers in the month.

C# Solution

Range is a static method available when you use System.Linq in C# 3.0. The example I will use here is how to fill a DropDownList with the numbers between 0 and 14. We simply need the numbers zero to fourteen in our drop down. The following code is serviceable and easy to understand.

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

        // Create two int[] arrays, then initialize them with all
        // the required numbers.
        int[] coords1 = new int[15];
        int[] coords2 = new int[15];
        for (int i = 0; i < 15; i++)
        {
            coords1[i] = i;
            coords2[i] = i;
        }

        // Set the DataSource on our ComboBox controls to the new arrays.
        // This will populate them with all the integers.
        // (You may want to read more about DataSources.)
        xComboBox.DataSource = coords1;
        yComboBox.DataSource = coords2;
    }
}

That does seem like too many lines of code for just those numbers. There are other options, such as manually typing the numbers into the Visual Studio Designer. But, as aspiring programmers, we want the most elegant, simplest, and most fool-proof solution.

LINQ Approach

The programming term for notation that expresses an entire list at once is list comprehension. LINQ enables this with the static class called Enumerable. Be sure to include System.Linq in your file first. Let's look at the code using LINQ, which is shown in its entirety below.

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

        // 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();
    }
}

Conclusion

Let me extrapolate this problem and say our program is ten thousand times larger. Would you rather have ten thousand expressions, or 80,000 statements? That may be exaggerated, but as software becomes ever more complex, we need ways to simplify what was once complex.

Dot Net Perls is dedicated to sharing code and knowledge. It has
© 2007-2008 Sam Allen. All rights reserved.

Ads by The Lounge