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.IEnumerable
1[System.Int32]]' to type 'System.Int32[][]'.'
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();
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With