[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Initialize arrays with ranges or repeated values in C#

[Initialize arrays with ranges or repeated values in C#]

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 the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.