Click here to Skip to main content
15,891,529 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,I want to conver the array with type double to int;shoud I use a loop over the elements or there is a better way?what about coping two arrays of one type?thanks in advance
Posted
Updated 10-Aug-11 19:50pm
v2
Comments
walterhevedeich 11-Aug-11 1:52am    
I guess you have to loop over the elements. Just curious, why would you want to do that? By converting it to int, you have decreased the precision of the data type.
ready to learn 11-Aug-11 1:54am    
you are right.but I want to use that array to make a bitmap

Hi,

there are many possible solutions for this. Here is one:

C#
public static int[] ConvertDoubleArrayToIntArray(double[] adDoubleArray)
{
     return adDoubleArray.Select(d => (int)d).ToArray();
}


and use like this:

C#
double[] adDoubleArray = { 1.1d, 2.2d, 3.3d, 4.4d, 5.5d };
int[] aiIntArray = ConvertDoubleArrayToIntArray(adDoubleArray);
 
Share this answer
 
v2
It might be helpful,

Convert.ToInt32 [^]

an example,

static void Main(string[] args)
 {
     double[] myDoubleArray = { 114.4, 225.0, 11.7 };
     IList<Int32> myInt32List = new List<Int32>();
     Array.ForEach(myDoubleArray, item =>
     {
           myInt32List.Add(Convert.ToInt32(item));

      });
      Int32[] myInt32Array = myInt32List.ToArray();
 }


:)
 
Share this answer
 
Comments
C_Johnson 20-Sep-11 16:57pm    
Converting an integer to a double using Convert.ToInt32 is not a time efficient method. Although it does work it is not recommended, using a cast will do suffice e.g

myInt32List.Add((int)item);

This will allow the value to be directly copied to a new memory position. The reason you need to use the cast is because converting from double to a integer will cause a loss of data the cast says you accept this loss. The Convert.ToInt32 requires the data to be a transferred and operated on externally to produce the same results. In this case it is superfluous to the outcome.
I think you have no choice but to write some LINQ or a foreach to iterate over your list and convert one at a time.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900