Initializing Jagged Array with the same non-default value

57 Views Asked by At

I am trying to create a jagged array of 10 by 10 using Linq and I want to populate it (for now) all with the same letter (not character). However, I am having trouble figuring out how to populate it in the same Linq statement.

I currently have (similar to Initialize a Jagged Array the LINQ Way):

public static string[][] computerBoard = new string[10][]
    .Select(x => new string[10])
    .ToArray();

But that creates array of null strings. How to modify it to set all elements to the same value as "A"? Or should I use a double for loop to populate it?

I have tried doing this:

public static string[][] computerBoard = new string[10][]
    .Select(x => new string[10]
    .Select(y => y = "/*my letter*/"))
    .ToArray();

but it gives me an error:

CS0226: Cannot implicitly convert type 'System.Collections.Generic.Ienumerable[]' to 'string[][]'. An explicit conversion exists (are you missing a cast?)

2

There are 2 best solutions below

1
StriplingWarrior On BEST ANSWER

I think this is what you're going for:

public static string[][] computerBoard = Enumerable.Range(1, 10)
    .Select(x => Enumerable.Repeat("/*my letter*/", 10).ToArray())
    .ToArray();
0
gilliduck On

LINQ really isn't the right tool for this, it's used to iterate over existing collections. Think of it like a fancier foreach loop.

That being said, by usage of Enumerable.Range you can get what you want.

string[][] foo = Enumerable.Range(0, 10)
    .Select(i => Enumerable.Range(0, 10)
        .Select(j => "a")
        .ToArray())
    .ToArray();

This will give you a 10x10 array filled with nothing but the letter "a".

Additionally I'll note, that not only is LINQ generally the wrong tool for this, it also isn't very readable.