Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert LINQ returned value to 2D Array

I am working with two 2D arrays, actually:

MatrixAddition(int[][] a, int[][] b)

Adding two matrix using LINQ and returning them to 2D array format int[][]. LINQ result is ok, returned expected result, but can't helping myself to return them in int[][] format.

MatrixAddition()

 public static int[][] MatrixAddition(int[][] a, int[][] b)
 {
     return (int[][])a.Select((x, i) => x.Select((y, j) => a[i][j] + b[i][j]));
 }

Error: System.InvalidCastException: 'Unable to cast object of type 'd__52[System.Int32[],System.Collections.Generic.IEnumerable1[System.Int32]]' to type 'System.Int32[][]'.'

like image 283
sebu Avatar asked Jan 28 '23 07:01

sebu


2 Answers

Your current code, without the cast, returns enumerables nested in another enumerable. You need to convert both the inner enumerables and the outer enumerable to int[], and remove the cast:

return a.Select(
    (x, i) => x.Select((y, j) => a[i][j] + b[i][j]).ToArray()
).ToArray();
like image 140
Sweeper Avatar answered Jan 29 '23 20:01

Sweeper


You can't cast an enumerable into an 2d jagged array directly:

return Enumerable.Range(0, a.GetLength(0))
    .Select(i => Enumerable.Range(0, a.GetLength(1))
        .Select(j => a[i][j] + b[i][j])
        .ToArray()
    ).ToArray();
like image 21
Xiaoy312 Avatar answered Jan 29 '23 21:01

Xiaoy312