21

How I can convert an array of strings to list of int? (without converting them one by one with my own method)

From searching in google I've seen methods named ToList() and ConvetAll() but I cant typed them, why is that?

What I've tried is:

new list<int>((int[])s.Split(','));

and I'm getting error that i cant convert string[] to int[] :(

Liath
  • 9,913
  • 9
  • 51
  • 81

10 Answers10

42

There's a two-step process involved here. The first is to convert the strings to an integer, then convert the array to a list. If you can use LINQ, the easiest way is to use:

stringArray.Select(x => Int32.Parse(x)).ToList();
Daniel T.
  • 37,212
  • 36
  • 139
  • 206
  • 16
    or shorter: `stringArray.Select(Int32.Parse).ToList();` – BrokenGlass Sep 19 '11 at 01:49
  • 2
    In case anyone wants to include a `TryParse`to prevent exceptions: 'int i; List intList = stringArray.Split(',').Select(s => int.TryParse(s, out i) ? i : -1).ToList();` – red_dorian Jan 16 '17 at 11:07
19

Getting a hint from your code:

var listOfInts = s.Split(',').Select(Int32.Parse).ToList();
Jordão
  • 55,340
  • 13
  • 112
  • 144
1

Try Using

int x = 0; 

var intList= stringList.Where(str => int.TryParse(str, out x)).Select(str => x).ToList();
Joe
  • 7,113
  • 1
  • 29
  • 34
D Mishra
  • 1,518
  • 1
  • 13
  • 17
1

For VB.NET, I had to do it in a loop

Dim myList As New List(Of Integer)
For Each item As String In s.Split(",")
    myList.Add(Val(item))
Next

May have been able to work it out with some inbuilt function but didn't want to spend too much time on it.

Adam
  • 403
  • 3
  • 8
1
public List<int > M1()
{
    string[] s =(file path));
    Array.Sort(s);
    var c = new List<int>();
    foreach(string x in s)
    {
        c.Add(Convert.ToInt32(x));
    }
    return c;
}
Werner Henze
  • 16,404
  • 12
  • 44
  • 69
1

use the following code:

var list = s.Select(Int32.Parse).ToList();
MB_18
  • 1,620
  • 23
  • 37
1
var s = "1,2,3,4,5,6,7,8,9";
var result = s.Split(',').Select(Convert.ToInt32).ToList();
Adi Lester
  • 24,731
  • 12
  • 95
  • 110
unruledboy
  • 2,455
  • 2
  • 23
  • 30
0

Try it:

 var selectedEditionIds = input.SelectedEditionIds.Split(",").ToArray()
                        .Where(i => !string.IsNullOrWhiteSpace(i) 
                         && int.TryParse(i,out int validNumber))
                        .Select(x=>int.Parse(x)).ToList();
Abdus Salam Azad
  • 5,087
  • 46
  • 35
0

Assuming values is your list of strings:

int[] ints = new int[values.Count];

int counter = 0;
foreach (string s in values) {
    ints[counter++] = int.Parse(s);
}

Don't overcomplicate yourself :)

kprobst
  • 16,165
  • 5
  • 32
  • 53
-1

You should use Array.ConvertAll method. Array.ConvertAll converts an array of one type to an array of another.

Here is the code:

string[] strArray = new string[] { "1", "2", "3" };
int[] intArray = Array.ConvertAll(strArray, int.Parse);
MB_18
  • 1,620
  • 23
  • 37