Home > Net >  Convert a string value to Integer array
Convert a string value to Integer array

Time:10-30

I have class

public class Myclas
{
    public string EmpName{ get; set; }
    public string myStingId{ get; set; }      
}
    

I would like to convert this string (myStingId)to an int array.

int[] listOfMyValues = null;

listOfMyValue s=  Int32.Parse(myStingId,CultureInfo.InvariantCulture).ToArray();

i have tried the above and recieve an error int doesnt contain a definition for array.

CodePudding user response:

A single string cannot be converted to an int[] without additional info about how. The string could be "123" and you want an array [1, 2, 3] or you want an array that contains a single int.

However, option 1)

int[] array = myStingId.Select(c => int.Parse(c.ToString(), CultureInfo.InvariantCulture)).ToArray(); 

Option 2)

int[] array = new[]{ int.Parse(myStingId, CultureInfo.InvariantCulture) };

CodePudding user response:

May be my solution is over engineered, but here is the alternate way

string myStingId = "6299857"
int[] result = Array.ConvertAll(myStingId.ToCharArray(), 
         x => int.Parse(x.ToString(), , CultureInfo.InvariantCulture));

Output:

[6, 2, 9, 9, 8, 5, 7]

Try Online

  • Related