Click here to Skip to main content
15,390,197 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a int Array and now I wnat convert it to long type.

So How must I do?
could help me please.
thanks.
Posted

In the .NET framework version 2.0, Microsoft added a generic method named ConvertAll to the Array class. This method allows an entire array to be converted from one data type to another. The method creates a new array, loops through the existing array and executes a delegate for each element. The resultant value from the delegate is stored in the new array, which becomes the method's return value.

The syntax for the ConvertAll method is as follows:

result = Array.ConvertAll<input-type, output-type>(input-array, converter);
The four changeable elements in the syntax are:

-input-type. The type of the items held in the input array.
-output-type. The type of the items to be created in the returned array.
-input-array. The array to duplicate and convert. This must be a one-dimensional, zero-based array.
-converter. A delegate containing the code to use to convert each of the items in the array. This may be as simple as a cast operation or be much more complicated, perhaps converting each numeric value to its English text equivalent as a string. The delegate must accept a parameter of the input data type and return a result of the output data type.


int[] integerArray = new int[] { 1, 2, 3, 4, 5 };

long[] longArray = Array.ConvertAll<int, long>(integerArray,
    delegate(int i)
    {
        return (long)i;
    });
   
v2
Comments
Mike Hankey 3-Mar-11 20:52pm
   
I guess we posted at the same time.
   
You were sooner, good answer, my 5.
--SA
ngthtra 6-Mar-11 20:06pm
   
thnaks very much!
Check out Array.ConvertAll, I believe that will do it.
   
Comments
Orcun Iyigun 3-Mar-11 20:50pm
   
what is the difference between mine and your answer ? :)
   
Good, my 5. (no difference, you probably did it at the same time, almost).
--SA
Mike Hankey 3-Mar-11 21:36pm
   
Thanks...Yeah I had the editor open and was off double checking and it took a couple of minute, it happens.
Your's is the better answer I'm glad you got the credit.
Orcun Iyigun 4-Mar-11 11:43am
   
it is fine I was just like two same answers for a question. you had credit as well. my 5 to you as well :)
Similar to Orcun's answer but uses a lambda. (.NET 3.5 or higher)
int[] a = { 2, 4, 6, 8, 10 };
long[] b = Array.ConvertAll(a, val => (long)val);

Please note that this makes an entire copy of the array and so it might not be efficient in some cases.
   

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