0

I'd like to declare an array of int rows with a variable size (X) and init all values to 1. For the moment I use this :

int[] rows = new int[X];
for (int i = 0; i < rows.Length; i++)
{
   rows[i] = 1;
}

Is there any faster/shorter way to do it with some sort of fill(1) or int[] rows = new int[X] {1}; ?

Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142

1 Answers1

1

LINQ:

int[] rows = Enumerable.Repeat(element:1, count: X).ToArray();// named parameter -  X
                                                              // doesn't tell anything
  • 1
    As Eric Lippert notes, doing this is [tens of times slower than simply writing a loop](http://stackoverflow.com/questions/1897555/what-is-the-equivalent-of-memset-in-c#comment1804854_1897564) (it [actually is](http://stackoverflow.com/a/1051227/11683)). – GSerg Nov 04 '14 at 09:58