Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

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.

like image 799
Sarp Kaya Avatar asked Nov 20 '25 17:11

Sarp Kaya


2 Answers

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.

like image 63
yamen Avatar answered Nov 23 '25 07:11

yamen


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;
    }
}
like image 23
Wormbo Avatar answered Nov 23 '25 07:11

Wormbo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!