3

I have something like

var a = new object[2]
{
     new double[1] { 0.5 },
     new double[1] { 0.5 }
}

And I want to cast this to double[][]. I tried (double[][])a and a.Cast<double[][]>() but it didnt work

3
  • It isn't either of things though. For example, you could write a[0] = "Hello"; and that would be entirely valid. Commented Jan 23, 2023 at 12:42
  • When you know for sure its a double[][] so you can cast it why isn't it of that type in the first place? Commented Jan 23, 2023 at 12:49
  • @Ralf because I get the result from an external API, that could only pass me objects Commented Jan 23, 2023 at 12:53

2 Answers 2

6

Your attempt of doing a.Cast<double[][]>() is almost correct. You can use:

double[][] b = a.Cast<double[]>().ToArray();

Explanation:

  • The problem is that the elements of your list are double[]s, but they are statically typed as object. To change the static type of a list's elements, you use LINQ's Cast<T>.
  • Cast<T> takes the type of the element as T, not the type of the resulting list (this is why your attempt to use Cast<double[][]>failed). Cast<double[]> yields an IEnumerable<double[]>.
  • To convert this IEnumerable<double[]> to an array of double[] (i.e., a double[][]), we can use LINQ's ToArray().

Note that this will

  • create a new outer array (i.e., object.ReferenceEquals(a, b) is false), but
  • the new outer array will reference the same inner arrays (i.e., object.ReferenceEquals(a[0], b[0]) is true).
Sign up to request clarification or add additional context in comments.

Comments

2

You can use LINQ double[][] b = a.Select(x => (double[])x).ToArray();

another way is to use Array.ConvertAll method, It takes a callback function which is called for each element in the given array.

double[][] b = Array.ConvertAll(a, x => (double[])x);

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.