Click here to Skip to main content
15,896,496 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi there,I have my array
string[]myNumber=new string[]{"1,2,5,4,6,"};


how can i convert above array to:

int[]number=new int[]{1,2,5,4,6,};


Note that i have tried to use myNumbers.CopyTo(number,0),it failed with a system warning that the two array must be of the same type and size.

Or is there any other way i can use, like List<> to achieve this function.

My aim is to convert the string array to int[]

Thanks in advance
Yours Martin
Posted
Updated 20-Jul-11 6:49am
v2

Try
string[] myNumber=new string[]{"1,2,5,4,6,"};
string[] arr = String.Split(myNumber[0]);
int[] intarr = new intarr[arr.count];
foreach(string str in arr)
{
   intarr[count++] = Convert.ToInt(str);
}
 
Share this answer
 
Comments
Uday P.Singh 20-Jul-11 13:30pm    
good one my 5!
Abhinav S 20-Jul-11 13:59pm    
Thank you!
Gordon Beeming 20-Jul-11 15:26pm    
your method ignores the fact that there could be more items in the array. If there is only going to be the one item the OP might as well be using a single string and not an array
public int[] StringToInt(string[] arr)
{
int i;
List<int> result = new List<int>();
for(int x=0;x < arr.Length; x++)
{
    if (int.TryParse(arr[x], out i))
        result.Add(i);
}
return result.ToArray();
}
</int></int>


This will be just a little safer in case an invalid string is parsed in.
 
Share this answer
 
Comments
Gordon Beeming 20-Jul-11 15:21pm    
my votes a 5, safe and will work great
fcronin 20-Jul-11 16:19pm    
So, you think his array is still fine for what hes trying to do, and this will work... ok, send his array to this method and let us know the result.
fcronin 20-Jul-11 16:26pm    
dominic - I think your method is fine by the way... for an array of the type I mention... good one. :)
First, the way you intialized your string array, you created one string of "1,2,3,4,5" ... not five individual strings. :)

But... here is one way to do it...

C#
string[] strValues = new string[] { "1", "2", "3", "4", "5" };
int[] intValues = strValues.Select(val => Convert.ToInt32(val)).ToArray();
 
Share this answer
 
Comments
Gordon Beeming 20-Jul-11 15:23pm    
technically the OP's array is still fine

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