19

Possible Duplicate:
How do I quicky fill an array with a specific value?

Is there a way to initialize an integer array with a single value like -1 without having to explicitly assign each item?

Basically, if I have

int[] MyIntArray = new int[SomeCount];

All items are assigned 0 by default. Is there a way to change that value to -1 without using a loop? or assigning explicitly each item using {}?

Community
  • 1
  • 1
Farhan Hafeez
  • 604
  • 1
  • 6
  • 21
  • 4
    Also check out this http://stackoverflow.com/questions/13980570/how-to-intialize-integer-array-in-c-sharp/ which discusses how to do it efficiently and http://stackoverflow.com/questions/10519275/high-memory-consumption-with-enumerable-range how not to use ToArray for large arrays. – Alexei Levenkov Jan 08 '13 at 07:55

3 Answers3

44
int[] myIntArray = Enumerable.Repeat(-1, 20).ToArray();
Eren Ersönmez
  • 37,498
  • 7
  • 66
  • 91
scartag
  • 17,085
  • 3
  • 45
  • 50
18

You could use the Enumerable.Repeat method

int[] myIntArray = Enumerable.Repeat(1234, 1000).ToArray()

will create an array of 1000 elements, that all have the value of 1234.

SWeko
  • 29,624
  • 9
  • 71
  • 103
14

If you've got a single value (or just a few) you can set them explicitly using a collection initializer

int[] MyIntArray = new int[] { -1 };

If you've got lots, you can use Enumerable.Repeat like this

int[] MyIntArray = Enumerable.Repeat(-1, YourArraySize).ToArray();
Habib
  • 212,447
  • 27
  • 392
  • 421
mlorbetske
  • 5,419
  • 1
  • 27
  • 40