Casting of int array into double array in immediate window?
Asked Answered
S

2

12

Is it possible to cast int array into double array in immediate window? I tried to cast but somehow its not working. I would like to know that is it possible or not?

Saharan answered 19/2, 2014 at 14:11 Comment(0)
O
25

That cast is illegal. Just try to compile it and you will see that it doesn't work either.

The following code will perform this conversion:

var d = i.Select(x => (double)x).ToArray();

Unfortunately, you can't use it in the immediate window because it doesn't support lambda expressions.

A solution that doesn't require lambda expressions is the following:

i.Select(Convert.ToDouble).ToArray();

This could work because there is no lambda expression. Thanks to Chris for the idea.

Overzealous answered 19/2, 2014 at 14:13 Comment(5)
Would using Convert.ToDouble instead of the Lambda do the trick?Modulus
@Chris: You mean as in i.Select(Convert.ToDouble).ToArray()? Yes, that could very well work.Overzealous
That is what I was thinking, yes. I've not got stuff open to test and I wasn't sure how up to the overload resolution it is when passing methods like that.Modulus
Well that's 50 rep I missed out on. ;-) Glad it worked though. For what its worth the thought process was "Lambdas aren't allowed. You could do it if you had a method already but then you'd have to write one and it takes away the point. Wait, what if there already was a method to convert between types?"Modulus
Of course this solution creates an array with a binary appearance that is very different from the original. If you wanted the same bits (but completely different numerical/mathematical meaning), you would need an array of type long[] instead, and then use longArr.Select(BitConverter.Int64BitsToDouble).ToArray().Admixture
P
11

One more way is to use Array.ConvertAll

Array.ConvertAll<int, double>(nums, x => x);
Pantywaist answered 15/4, 2019 at 19:13 Comment(1)
Love this suggestion! Should be faster than the LINQ solution given above.Homogeneity

© 2022 - 2024 — McMap. All rights reserved.