Is there an easy way to create an initialized array?

I want to create an array of int [n] unique numbers:

int[] result = new int[24];

for(int i = 0; i<24; i++)
    result[i] = 1;

return result;

Is there a shorter way for this. Maybe something like this:

return (from i in new int[24] 
        select 1).ToArray();

But not as ugly as that.

+3
source share
2 answers

I'm not sure how to make them all “1” makes them unique, but this will make the equivalent of your code:

return Enumerable.Repeat(1, 24).ToArray();
+11
source

The code you posted does not seem to match the name of the question, but this will do the same as your snippet:

Enumerable.Repeat(1, 24).ToArray()
+5
source

Source: https://habr.com/ru/post/1758686/


All Articles