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
CodePudding user response:
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 asobject
. To change the static type of a list's elements, you use LINQ'sCast<T>
. Cast<T>
takes the type of the element asT
, not the type of the resulting list (this is why your attempt to useCast<double[][]>
failed).Cast<double[]>
yields anIEnumerable<double[]>
.- To convert this
IEnumerable<double[]>
to an array ofdouble[]
(i.e., adouble[][]
), we can use LINQ'sToArray()
.
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).
CodePudding user response:
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);