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.
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.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With