4

Having the following code is there a leaner way of initializing the array from 1 to the number especified by a variable?

int nums=5;
int[] array= new int[nums];

for(int i=0;i<num;i++)
{
   array[i] = i;
}

Maybe with linq or some array.function?

4 Answers 4

6
int[] array = Enumerable.Range(0, nums).ToArray();
Sign up to request clarification or add additional context in comments.

6 Comments

This might create an array which allocates too much memory. ToArray does not know how many elements are in Enumerable.Range. Hence it needs to foreach all of them and always increase the capacity(using a doubling algorith). So you might end with an array which consumes nearly twice as much memory as necessary. –
@TimSchmelter Is there then some alternative as simple as this but with less resource consumption? (in my case the range would go to 30 at max...)
@ase69s If only 30 entries, then don't worry about it. EDIT: Otherwise, all I can think of is pre-initializing something like a List to your capacity: var items = new List<int>(nums);items.AddRange(Enumerable.Range(0, nums));
Here's a question related to this issue: High memory consumption with Enumerable.Range? @ase69s: You don't need to care if you only have 30 items.
thank you all for your detailed explanations ^^, answer accepted then
|
1

Use Enumerable.Range() method instead of. Don't forget to add System.Linq namespace. But this could spend little bit high memory. You can use like;

int[] array = Enumerable.Range(0, nums).ToArray();

Generates a sequence of integral numbers within a specified range.

1 Comment

Also, ToArray does not know how many elements are in Enumerable.Range. Hence it needs to foreach all of them always increasing the capacity(using a doubling algorith). So you might end with an array which consumes nearly twice as much memory as necessary. Here's my own question regarding this issue: High memory consumption with Enumerable.Range?
0

Using Enumerable.Range

int[] array = Enumerable.Range(0, nums).ToArray();

Comments

0

Maybe I'm missing something here, but here is the best way I know of:

int[] data = new int [] { 383, 484, 392, 975, 321 };

from MSDN

even simpler:

int[] data = { 383, 484, 392, 975, 321 };

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.