Create an Array of size N and with all the elements equals to 2

Viewed 47

I'm using C#. I want to create an integer array of N elements, all with the same value:

int[] array = new int[N] {2};

But that code doesn't work.

N is an integer within the range [1..100,000]

How can I do it?

3 Answers

If you want to do this fast then you need to go the old school Array class and use the relatively new Fill method:

int[] array = new int[100_000];
Array.Fill(array, 2);

There is a LINQ alternative that is also quite nice:

int[] array = Enumerable.Repeat(2, 100_000).ToArray();

But, to be fair, under-the-hood it uses Array.Fill(array, _current); anyway.

You can do that with LINQ:

var array = Enumerable
    .Range(1, 100_000)
    .Select(x => 2)
    .ToArray();

C# doesn't have array initialization shortcut similar to that as in other languages. You can fill it in a loop, or use Linq with Enumerable.Range. ie:

int N = 10;
var array = Enumerable.Range(1, N).Select(e => 2).ToArray();
Related