0

Besides using a loop. An int array can be initialized with 0s easy like arr = Enumerable.Range(0, 100).Select(i => new int[100]).ToArray();.

Is there a way I can initialize a string or char array in a similar fashion?

3
  • Plug string or char into your expression where you have int. What did you get? Is it what you want? Commented Apr 28, 2012 at 3:21
  • What's the result you're looking for? Commented Apr 28, 2012 at 3:22
  • I just want to initialize it with string 0s but instead I get a bunch of nulls when I write to the text file. Commented Apr 28, 2012 at 3:32

1 Answer 1

2

I think you're looking for:

string[] arrayOfStringZeros = Enumerable.Range(0, 100)
                                        .Select(i => "0")
                                        .ToArray();


char[] arrayOfCharZeros = Enumerable.Range(0, 100)
                                   .Select(i => '0')
                                   .ToArray();

Updated

char[][] jaggedOfCharZeros = Enumerable.Range(0, 100)
                                       .Select(i => Enumerable.Range(0, 100)
                                                              .Select(j => '0')
                                                              .ToArray())
                                       .ToArray();

Actually it would probably be slightly more efficient to do:

char[] initZeros = Enumerable.Range(0, 100)
                             .Select(i => '0')
                             .ToArray();


char[][] jaggedOfCharZeros = Enumerable.Range(0, 100)
                                       .Select(i => (char[])initZeros.Clone())
                                       .ToArray();
Sign up to request clarification or add additional context in comments.

4 Comments

But how would I do that for a jagged array?
Ok that works, I see how it's done. Thanks. But the inner i should be a j or something or it'll conflict.
I added a slightly better version.
Beware, the second, "better", version adds a reference to the same char array to each first dimension index of the 2D array, insread of a new instance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.