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?
Casting of int array into double array in immediate window?
Asked Answered
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.
@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 One more way is to use Array.ConvertAll
Array.ConvertAll<int, double>(nums, x => x);
Love this suggestion! Should be faster than the LINQ solution given above. –
Homogeneity
© 2022 - 2024 — McMap. All rights reserved.
Convert.ToDouble
instead of the Lambda do the trick? – Modulus