Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a int array into a long array in C#?

Tags:

arrays

c#

I want to convert my ordered int array into a long array, this is what my my conversion currently looks like:

long[] arraylong = new long[array.Length];

my issues arise when I want to apply this calculation:

longmid = lowlong + ((searchValueLong - arraylong[lowlong]) * (highlong - lowlong)) 
    / (arraylong[highlong] - arraylong[lowlong]);

and I get an exception of type DivideByZeroException. The values that are zero after the conversion are arraylong[lowlong] and arraylong[highlong]

Thank you in advance for any help you may be able to give.

like image 431
L. Full Avatar asked Dec 14 '22 23:12

L. Full


1 Answers

To convert the int[] use linqs Select and in it explicitly cast to long:

int[] ints = new int[] { 1, 2, 3, 4 };
var longs = ints.Select(item => (long)item).ToArray();

In your code above you've only initialized a long[] to the size of the int[] and the items get the default value - which for long is zero - causing your DivideByZeroException


Note that using ints.Cast<long>().ToArray(); will not work and throw an InvalidCastException: Specified cast is not valid.

like image 50
Gilad Green Avatar answered Dec 24 '22 08:12

Gilad Green