What is the easiest way to build an array of integers starting at 0 and increasing until a given point?

Background: I have a struct that holds an int[] representing indexes of other arrays.

I would like to signify I want to use all indexes by filling this array with ints starting at 0 and increasing until int numTotalIndexes; I am sure there is a better way to do this than using a for loop.

Someone here showed me this little Linq trick

int[] numContacts = new int[]{ 32, 48, 24, 12};
String[][] descriptions = numContacts.Select(c => new string[c]).ToArray();

to build a jagged 2D array without loops (well it does, but it hides them and makes my code pretty) and I think there might be a nice little trick to accomplish what I want above.

有帮助吗?

解决方案

You can use Enumerable.Range:

int[] intArray = Enumerable.Range(0, numTotalIndexes).ToArray();

You:

I am sure there is a better way to do this than using a for loop

Note that LINQ also uses loops, you simply don't see them. It's also not the most efficient way since ToArray doesn't know how large the array must be. However, it is a readable and short way.

So here is the (possibly premature-)optimized, classic way to initialize the array:

int[] intArray = new int[numTotalIndexes];
for(int i=0; i < numTotalIndexes; i++)
    intArray[i] = i;

其他提示

I'm not sure i understand your question at all but if going by your first line what you want is

var MySequencialArray = Enumerable.From(0,howmanyyouwant).ToArray();
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top