Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to create an array with non-default repeated values in C#?
We can create an array with non-default repeated values using Enumerable.Repeat(). This method creates a sequence that contains one repeated value a specified number of times. It requires the System.Linq namespace to be included.
Syntax
Following is the syntax for using Enumerable.Repeat() −
IEnumerable<T> Enumerable.Repeat<T>(T element, int count)
Parameters
-
element − The value to be repeated in the sequence.
-
count − The number of times to repeat the value in the generated sequence.
Return Value
Returns an IEnumerable<T> that contains a repeated value. To convert it to an array, use the ToArray() method.
Using Enumerable.Repeat() with IEnumerable
The Enumerable.Repeat() method returns an IEnumerable sequence that can be iterated directly −
using System;
using System.Linq;
class Program {
static void Main(string[] args) {
var values = Enumerable.Repeat(10, 5);
foreach (var item in values) {
Console.WriteLine(item);
}
}
}
The output of the above code is −
10 10 10 10 10
Using Enumerable.Repeat() to Create an Array
To create an actual array with repeated values, call ToArray() on the result −
using System;
using System.Linq;
class Program {
static void Main(string[] args) {
int[] values = Enumerable.Repeat(10, 5).ToArray();
Console.WriteLine("Array length: " + values.Length);
foreach (var item in values) {
Console.WriteLine(item);
}
}
}
The output of the above code is −
Array length: 5 10 10 10 10 10
Using Enumerable.Repeat() with Different Data Types
The method works with any data type, including strings, objects, and custom types −
using System;
using System.Linq;
class Program {
static void Main(string[] args) {
// String array with repeated values
string[] names = Enumerable.Repeat("Hello", 3).ToArray();
Console.WriteLine("String array:");
foreach (string name in names) {
Console.WriteLine(name);
}
// Boolean array with repeated values
bool[] flags = Enumerable.Repeat(true, 4).ToArray();
Console.WriteLine("\nBoolean array:");
foreach (bool flag in flags) {
Console.WriteLine(flag);
}
// Double array with repeated values
double[] prices = Enumerable.Repeat(99.99, 2).ToArray();
Console.WriteLine("\nDouble array:");
foreach (double price in prices) {
Console.WriteLine(price);
}
}
}
The output of the above code is −
String array: Hello Hello Hello Boolean array: True True True True Double array: 99.99 99.99
Conclusion
The Enumerable.Repeat() method provides an efficient way to create arrays or sequences with repeated non-default values in C#. It works with any data type and can be easily converted to an array using ToArray() for scenarios requiring indexed access or array-specific operations.
