2

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.

0

4 Answers 4

7

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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;
    }
}

Comments

1

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);

Comments

1

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();

1 Comment

This is my favourite answer, I've never heard of Array.ConvertAll before!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.