Anders Gustafsson
Anders Gustafsson

Reputation: 15971

Initializing a C# array with multiple copies of the same element

In the C++ Standard Template Library (STL), it is possible for example to create a vector consisting of multiple copies of the same element, using this constructor:

std::vector<double> v(10, 2.0);

This would create a vector of 10 doubles, initially set to 2.0.

I want to do a similar thing in C#, more specifically creating an array of n doubles with all elements initialized to the same value x.

I have come up with the following one-liner, relying on generic collections and LINQ:

double[] v = new double[n].Select(item => x).ToArray();

However, if an outsider would read this code I don't think it would be immediately apparent what the code actually does. I am also concerned about the performance, I suppose it would be faster to initialize the array elements via a for loop (although I haven't checked). Does anybody know of a cleaner and/or more efficient way to perform this task?

Upvotes: 33

Views: 32659

Answers (6)

Cole Cameron
Cole Cameron

Reputation: 2233

Later versions of .NET have introduced an Array.Fill method. See usage:

double[] v = new double[n];
Array.Fill(v, 2.0);

Upvotes: 3

VB.net Coder
VB.net Coder

Reputation: 17

In VB.NET

Imports System.Linq

Dim n As Integer = 10

Dim colorArray = New Color(n - 1) {}.[Select](Function(item) Color.White).ToArray()

Upvotes: -2

Thomas Levesque
Thomas Levesque

Reputation: 292365

What about this?

double[] v = Enumerable.Repeat(x, n).ToArray();

EDIT: I just did a small benchmark; to create 1000 arrays of 100000 elements each, using a loop is about 3 times faster that Enumerable.Repeat.

Repeat 
00:00:18.6875488 

Loop 
00:00:06.1628806 

So if performance is critical, you should prefer the loop.

Upvotes: 50

sll
sll

Reputation: 62484

double[] theSameValues = Enumerable.Repeat(2.0, 10).ToArray();

Upvotes: 2

Massimiliano Peluso
Massimiliano Peluso

Reputation: 26717

the for each (or better the classic for) is always much faster than using Linq. You should use the Linq expression only if it makes the code more readable

Upvotes: -1

Marc Gravell
Marc Gravell

Reputation: 1062550

var arr = Enumerable.Repeat(x, n).ToArray();

Personally, I'd just use a regular array loop, though:

var arr = new double[n];
for(int i = 0 ; i < arr.Length ; i++) arr[i] = x;

More characters, but the array is demonstrably the right size from the outset - no iterative growth List<T>-style and final copy back. Also; simply more direct - and the JIT can do a lot to optimise the for(int i = 0 ; i < arr.Length ; i++) pattern (for arrays).

Upvotes: 9

Related Questions