4

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[][]'.'

2 Answers 2

5

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();
Sign up to request clarification or add additional context in comments.

Comments

3

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();

Comments

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.