Linq Convert String Array To Int Array

Linq Convert String Array To Int Array

C# Convert array of string to array of int. You want to convert an array of string to array of integer. Here are programs in C#.net and VB.net which shows how to convert string array to int array.

C#.net program convert String array To Int Array.

void Main()
{

    string []arrOfString = new string[] { "10","25","96","45","78" };
    int []arrOfInteger = arrOfString.Select( s => int.Parse(s)).ToArray() ;
    
}


Vb.net convert string array to int array.

Private Sub Main()

	Dim arrOfString As String() = New String() {"10", "25", "96", "45", "78"}
	Dim arrOfInteger As Integer() = arrOfString.[Select](Function(s) Integer.Parse(s)).ToArray()
	
End Sub

Output.

10
 
25
 
96
 
45
 
78

In above program, Select is an extension where we have called anonymous method s goes to int.Parse(s).

You might have received string containing integers separated by pipe operator “|”. Let’s see how to convert string into array of strings and then convert array of string into array of integers.

C#.Net Convert string array to int array example.

void Main()
{

    string responseString = "10|25|2012|56|89|70";
    int []arrOfInteger = responseString.Split("|".ToCharArray()).Select( s => int.Parse(s)).ToArray() ;

}

Vb.net convert string array to int array example.

Private Sub Main()

	Dim responseString As String = "10|25|2012|56|89|70"
	Dim arrOfInteger As Integer() = responseString.Split("|".ToCharArray()).[Select](Function(s) Integer.Parse(s)).ToArray()

End Sub

C# Convert string array to int array with Try Parse example.

void Main()
{

    string responseString = "sss|10|25|2012|56|89|70|xxx";
    int x;
    int []arrOfInteger = responseString.Split("|".ToCharArray()).Select( s => int.TryParse(s, out x) ? x : 0 ).ToArray() ;
    
    foreach(int n in arrOfInteger)
    {
     Console.WriteLine(n);
    }
    
}


VB.net convert string array to int array with Try Parse example.

Private Sub Main()

	Dim responseString As String = "sss|10|25|2012|56|89|70|xxx"
	Dim x As Integer
	Dim arrOfInteger As Integer() = responseString.Split("|".ToCharArray()).[Select](Function(s) If(Integer.TryParse(s, x), x, 0)).ToArray()

	For Each n As Integer In arrOfInteger
		Console.WriteLine(n)
	Next

End Sub

output.

0
10
25
2012
56
89
70
0

Description.

Using Try Parse we are handling the exception of type can't invalid string format. This is the correct method for converting string array to int array.

Tags: