Problem
I have a string representation of an array of integers:
var arr = new string[] { "1", "2", "3", "4" };
To push it any farther, I’ll need an array of’real’ integers:
void Foo(int[] arr) { .. }
I attempted to cast int, but it failed:
Foo(arr.Cast<int>.ToArray());
What I can do next is:
var list = new List<int>(arr.Length);
arr.ForEach(i => list.Add(Int32.Parse(i))); // maybe Convert.ToInt32() is better?
Foo(list.ToArray());
or
var list = new List<int>(arr.Length);
arr.ForEach(i =>
{
int j;
if (Int32.TryParse(i, out j)) // TryParse is faster, yeah
{
list.Add(j);
}
}
Foo(list.ToArray());
However, both appear to be unattractive.
Is there another method to finish the job?
Asked by abatishchev
Solution #1
The Array can be used with an array. Method ConvertAll:
int[] myInts = Array.ConvertAll(arr, s => int.Parse(s));
Marc Gravell pointed out that the lambda can be eliminated, resulting in the following shorter version:
int[] myInts = Array.ConvertAll(arr, int.Parse);
A LINQ solution is similar, except that to acquire an array, you’ll need to add the ToArray call:
int[] myInts = arr.Select(int.Parse).ToArray();
Answered by Ahmad Mageed
Solution #2
EDIT: to convert to array
int[] asIntegers = arr.Select(s => int.Parse(s)).ToArray();
This ought to suffice:
var asIntegers = arr.Select(s => int.Parse(s));
Answered by Simon Fox
Solution #3
Here are some tips for avoiding exceptions when using.Parse. Alternatives to TryParse
Only parsable items should be used:
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 to utilizing 0 for non-parsable components include:
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);
Answered by Slai
Solution #4
You can easily convert a string array to an int array by using the following formula:
var converted = arr.Select(int.Parse)
Answered by A.Dara
Solution #5
var asIntegers = arr.Select(s => int.Parse(s)).ToArray();
You must ensure that you do not receive an IEnumerableint> as a response.
Answered by Rob
Post is based on https://stackoverflow.com/questions/1297231/convert-string-to-int-in-one-line-of-code-using-linq