Initialize arrays with ranges or repeated values in C#

[Initialize arrays]

This example uses the Enumerable class’s shared methods to initialize arrays to ranges or repeated values. The methods return IEnumerable results. You can then use the result’s ToArray and ToList methods to convert the IEnumerable into an array or list.

When the program starts, it executes the following code to initialize the program’s ListBoxes.

private void Form1_Load(object sender, EventArgs e)
    // 101, 102, 103, ... 120.
    int[] array_range =
        Enumerable.Range(101, 20).ToArray();
    lstArrayRange.DataSource = array_range;

    // 1001, 1002, 1003, ... 1020.
    List<int> list_range =
        Enumerable.Range(1001, 20).ToList();
    lstListRange.DataSource = list_range;

    // Pi, Pi, Pi, ... Pi.
    double[] array_repeat =
        Enumerable.Repeat(Math.PI, 20).ToArray();
    lstArrayRepeat.DataSource = array_repeat;

    // Apple, Apple, Apple, ... Apple.
    List<string> list_repeat =
        Enumerable.Repeat("Apple", 20).ToList();
    lstListRepeat.DataSource = list_repeat;

This code uses Enumerable methods to make:

  • An array holding the values 101 through 120.
  • A List holding the values 1001 through 1020.
  • An array of double holding 20 copies of the value π.
  • A List holding 20 copies of the string “Repeat.”

The program displays each of the arrays and lists in ListBoxes so you can see their values.

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in arrays, variables. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.