I like to create an int[]
with length X
and value it with [0,1,2....X]
e.g.
public int[] CreateAA(int X){}
int[] AA = CreateAA(9) => [0,1,2,3,4,5,6,7,8,9]
is there any easy method? Or have to loop and init value
I like to create an int[]
with length X
and value it with [0,1,2....X]
e.g.
public int[] CreateAA(int X){}
int[] AA = CreateAA(9) => [0,1,2,3,4,5,6,7,8,9]
is there any easy method? Or have to loop and init value
To initialize try this
with function and loop:
Why make a function when it is already there.
For this specific example, use
where
0 is the starting value
and10 (X + 1) is the length of array
So a general one applicable to all
You can avail the functionality of IEnumerable.
This will create a IEnumerable List for you and
.ToArray()
will satisfy your int array need.So for X=9 in your case it would generate the array for
[0,1,2,3,4,5,6,7,8,9]
(as you need)For completeness, here is a function that creates an array.
I made it a bit more versatile by having parameters for the min and max value, i.e.
CreateArray(0, 9)
returns{0,1,2,3,4,5,6,7,8,9}
.Using
Enumerable.Range(0, 10).ToArray()
is very concise but if you want to create a very large array theToArray
extension method will have to collect the numbers into a buffer that will have to be reallocated multiple times. On each reallocation the contents of the buffer is copied to the new larger buffer. .NET uses a strategy where the size of the buffer is doubled on each reallocation (and the initial buffer has four items).So if you want to avoid multiple reallocations of the buffer you need to create the array in advance:
This is the most efficient way of initializing the array.
However, if you need an array of say 100,000,000 consecutive numbers then you should look at a design where you don't have to keep all the numbers in an array to avoid the impact of the memory requirement.
IEnumerable<int>
is very useful for this purpose because you don't have to allocate the entire sequence but can produce it while you iterate and that is exactly whatEnumerable.Range
does. So avoiding the array of consecutive numbers in the first place may be even better than thinking about how to create it.