Sarp Kaya
Sarp Kaya

Reputation: 3784

How to define an array with equal value in c#?

I want to create a new array. Let's say

int[] clickNum = new int[800];

Then I want to do something like clickNum = 2, which would make all array elements starting from clickNum[0] to clickNum[800], set to 2. I know there's a way to do it by using a loop; but what I am after is just a function or a method to do it.

Upvotes: 2

Views: 247

Answers (4)

Holf
Holf

Reputation: 6432

Using Array.ConvertAll should be more efficient if you are working with very large arrays and performance is a concern:

int[] clickNum = Array.ConvertAll(new int[800], x => x = 2);

And you can also use a standard LINQ Select if performance doesn't worry you:

int[] clickNum = new int[800].Select(x => x = 2).ToArray();

Upvotes: 1

Wormbo
Wormbo

Reputation: 4992

I don't think there's any built-in function to fill an existing array/list. You could write a simple helper method for that if you need the operation in several places:

static void Fill<T>(IList<T> arrayOrList, T value)
{
    for (int i = arrayOrList.Count - 1; i >= 0; i--)
    {
        arrayOrList[i] = value;
    }
}

Upvotes: 5

rtuner
rtuner

Reputation: 2410

I guess you are looking for a function you created but you do not have the time to type it. So if you want it in a single line, try:

for(int i = 0; i < clickNum.Length; i++, clickNum[i] = 2);

Upvotes: 1

yamen
yamen

Reputation: 15618

I suppose you could use Enumerable.Repeat when you initialise the array:

int[] clickNum = Enumerable.Repeat(2, 800).ToArray();

It will of course be slower, but unless you're going to be initiating literally millions of elements, it'll be fine.

A quick benchmark on my machine showed that initialising 1,000,000 elements using a for loop took 2ms, but using Enumerable.Repeat took 9ms.

This page suggests it could be up to 20x slower.

Upvotes: 7

Related Questions