3

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

int[] result = new int[24];

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

return result;

Is there a shorter way to accomplish this. May be something like this:

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

But not as ugly as this.

4
  • i.e. you want to create an array initialized with some number different from 0? Commented Aug 9, 2010 at 8:11
  • Did none of the answers on your other questions answer those? Commented Aug 9, 2010 at 8:11
  • Oh, and are we talking about random or sequential numbers? Commented Aug 9, 2010 at 8:12
  • 1
    for(int i = 0; i<24; i++) result[i] = 1; In this code you set all the numbers to 1. This is not unique but just initialized. Commented Aug 9, 2010 at 8:14

2 Answers 2

11

I'm not sure in what way making them all "1" makes them unique, but this will do the equivalent to your code:

return Enumerable.Repeat(1, 24).ToArray();
Sign up to request clarification or add additional context in comments.

2 Comments

+1 for flagging that this is only the equivalent to the example, not to what it seems like the OP is asking for. in that sense, it might be added that Enumerable.Range(0, 24).ToArray(); might be what OP is looking for, if we're allowed to assume a typo in both examples.
haha,just now I misunderstood OP's question and give the Enumerable.Range answer. He says "result[i] = 1" not "result[i] = i";
5

The code you posted doesn't seem to match the title of the question, but this will do the same as your snippet:

Enumerable.Repeat(1, 24).ToArray()

1 Comment

Sorry for my bad english. The question should be: Is there a simple way to create an array filled with a constant?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.