328

I have an array of integers in string form:

var arr = new string[] { "1", "2", "3", "4" };

I need to an array of 'real' integers to push it further:

void Foo(int[] arr) { .. }

I tried to cast int and it of course failed:

Foo(arr.Cast<int>.ToArray());

I can do next:

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());

but both looks ugly.

Is there any other ways to complete the task?

8

6 Answers 6

716

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();
8
  • 5
    Nice. Didn't know that one. +1
    – spender
    Aug 19, 2009 at 0:17
  • 87
    Actually, you don't need the lambda; ConvertAll(arr, int.Parse) is sufficient Dec 8, 2010 at 13:35
  • 1
    Lambda is needed in VB.Net 2010: uArray = Array.ConvertAll(sNums.Split(","), Function(i) UInteger.Parse(i))
    – BSalita
    Jan 15, 2012 at 15:24
  • 1
    @BSalita No, in VB.Net it's Array.ConvertAll(arr, AddressOf Integer.Parse)
    – Slai
    May 3, 2016 at 18:03
  • 1
    @AmrAlaa congrats, you're the first downvoter :) Seriously though, the original question shows an approach using TryParse, so if anyone wants to check for errors that's one option, with some drawbacks. I don't disagree with you; error checking is important, but I feel the answer was sufficient for the question and did not get exhaustive about error checking. StackOverflow should point you to a solution, but that doesn't mean it should be copy-pasted into our projects without reflection and enhancements as needed. Feb 22, 2019 at 18:45
36

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));
2
  • 1
    .ToArray() required to satisfy OP's question
    – spender
    Aug 19, 2009 at 0:13
  • 2
    change var to int[] and append .ToArray() if you need it as an int array
    – Simon Fox
    Aug 19, 2009 at 0:14
30

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);
7
  • The second solution: var a = Enumerable.Range(0, arr.Length).Where(i => int.TryParse(arr[i], out i)).ToArray(); just returns the indeces 0,1,2,... instead of the real values. What's the right solution here?
    – Beetee
    Jul 10, 2017 at 11:20
  • Thanks @Beetee. Not sure what I was thinking with that. I replaced it with another alternative.
    – Slai
    Jul 10, 2017 at 12:14
  • @Slai: Thanks. But what does new int[0]? When I have text, I don't get a 0 in my array...
    – Beetee
    Jul 11, 2017 at 8:13
  • @Beetee new int[0] is an empty int array. The first two examples skip values that can't be parsed, and the last two examples use 0 for values that can't be parsed.
    – Slai
    Jul 11, 2017 at 11:12
  • @Slai: Ah now I get it. I mixed it up with new int[] {0}. Thx.
    – Beetee
    Jul 11, 2017 at 13:10
14

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

var converted = arr.Select(int.Parse)
1
  • 6
    nice! thankyou. And in VB.Net Dim converted = arr.Select(addressof Integer.Parse)
    – Mafu Josh
    Mar 15, 2013 at 12:25
4
var asIntegers = arr.Select(s => int.Parse(s)).ToArray(); 

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

3
var list = arr.Select(i => Int32.Parse(i));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.