329

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
  • 3
    What's wrong with simply iterating through one collection, converting the value, and the adding it to the second? Seems pretty clear in intention to me. Commented Aug 19, 2009 at 0:11
  • 1
    Otherwise, msdn.microsoft.com/en-us/library/73fe8cwf.aspx Commented Aug 19, 2009 at 0:12
  • 1
    Just FYI, I'm using this question here: stackoverflow.com/questions/1297325/… Commented Aug 19, 2009 at 0:49
  • Related: convert string-array to int-array, fastest Commented Jun 21, 2010 at 10:07
  • 1
    TryParse is not faster (except if your strings are invalid, but in that case you want the exception to alert you). Commented Jun 9, 2012 at 18:34

6 Answers 6

719

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();
Sign up to request clarification or add additional context in comments.

8 Comments

Nice. Didn't know that one. +1
Actually, you don't need the lambda; ConvertAll(arr, int.Parse) is sufficient
Lambda is needed in VB.Net 2010: uArray = Array.ConvertAll(sNums.Split(","), Function(i) UInteger.Parse(i))
@BSalita No, in VB.Net it's Array.ConvertAll(arr, AddressOf Integer.Parse)
@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.
|
37

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 Comments

.ToArray() required to satisfy OP's question
change var to int[] and append .ToArray() if you need it as an int array
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 Comments

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?
Thanks @Beetee. Not sure what I was thinking with that. I replaced it with another alternative.
@Slai: Thanks. But what does new int[0]? When I have text, I don't get a 0 in my array...
@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: Ah now I get it. I mixed it up with new int[] {0}. Thx.
|
14

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

var converted = arr.Select(int.Parse)

1 Comment

nice! thankyou. And in VB.Net Dim converted = arr.Select(addressof Integer.Parse)
4
var asIntegers = arr.Select(s => int.Parse(s)).ToArray(); 

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

Comments

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.