c# - Convert string[] to int[] in one line of code using LINQ

ID : 10045

viewed : 24

Tags : c#.netlinqextension-methodsc#

Top 5 Answer for c# - Convert string[] to int[] in one line of code using LINQ

vote vote

94

Given an array you can use the Array.ConvertAll method:

int[] myInts = Array.ConvertAll(arr, s => int.Parse(s)); 

Thanks to Marc Gravell for pointing out that the lambda can be omitted, yielding a shorter version shown below:

int[] myInts = Array.ConvertAll(arr, int.Parse); 

A LINQ solution is similar, except you would need the extra ToArray call to get an array:

int[] myInts = arr.Select(int.Parse).ToArray(); 
vote vote

83

EDIT: to convert to array

int[] asIntegers = arr.Select(s => int.Parse(s)).ToArray(); 

This should do the trick:

var asIntegers = arr.Select(s => int.Parse(s)); 
vote vote

75

To avoid exceptions with .Parse, here are some .TryParse alternatives.

To use only the elements that can be parsed:

string[] arr = { null, " ", " 1 ", " 002 ", "3.0" }; int i = 0;  var a = (from s in arr where int.TryParse(s, out i) select i).ToArray();  // a = { 1, 2 } 

or

var a = arr.SelectMany(s => int.TryParse(s, out i) ? new[] { i } : new int[0]).ToArray(); 

Alternatives using 0 for the elements that can't be parsed:

int i;  var a = Array.ConvertAll(arr, s => int.TryParse(s, out i) ? i : 0); //a = { 0, 0, 1, 2, 0 } 

or

var a = arr.Select((s, i) => int.TryParse(s, out i) ? i : 0).ToArray(); 

C# 7.0:

var a = Array.ConvertAll(arr, s => int.TryParse(s, out var i) ? i : 0); 
vote vote

62

you can simply cast a string array to int array by:

var converted = arr.Select(int.Parse) 
vote vote

57

var asIntegers = arr.Select(s => int.Parse(s)).ToArray();  

Have to make sure you are not getting an IEnumerable<int> as a return

Top 3 video Explaining c# - Convert string[] to int[] in one line of code using LINQ

Related QUESTION?