Initialize a Jagged Array the LINQ Way Initialize a Jagged Array the LINQ Way arrays arrays

Initialize a Jagged Array the LINQ Way


double[][] myArr = Enumerable  .Range(0, rowCount)  .Select(i => new double[colCount])  .ToArray();


What you have won't work as the new occurs before the call to Repeat. You need something that also repeats the creation of the array. This can be achieved using the Enumerable.Range method to generate a range and then performing a Select operation that maps each element of the range to a new array instance (as in Amy B's answer).

However, I think that you are trying to use LINQ where it isn't really appropriate to do so in this case. What you had prior to the LINQ solution is just fine. Of course, if you wanted a LINQ-style approach similar to Enumerable.Repeat, you could write your own extension method that generates a new item, such as:

    public static IEnumerable<TResult> Repeat<TResult>(          Func<TResult> generator,          int count)    {        for (int i = 0; i < count; i++)        {            yield return generator();        }    }

Then you can call it as follows:

   var result = Repeat(()=>new double[rowCount], columnCount).ToArray();


The behavior is correct - Repeat() returns a sequence that contains the supplied object multiple times. You can do the following trick.

double[][] myArr = Enumerable    .Repeat(0, rowCount)    .Select(i => new double[colCount])    .ToArray();