Reputation:
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[] :(
Upvotes: 23
Views: 42931
Reputation: 2321
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);
Upvotes: -1
Reputation: 49
use the following code:
var list = s.Select(Int32.Parse).ToList();
Upvotes: 2
Reputation: 11
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;
}
Upvotes: 1
Reputation: 411
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.
Upvotes: 1
Reputation: 5512
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();
Upvotes: 0
Reputation: 1578
Try Using
int x = 0;
var intList= stringList.Where(str => int.TryParse(str, out x)).Select(str => x).ToList();
Upvotes: 1
Reputation: 2342
var s = "1,2,3,4,5,6,7,8,9";
var result = s.Split(',').Select(Convert.ToInt32).ToList();
Upvotes: 1
Reputation: 56537
Getting a hint from your code:
var listOfInts = s.Split(',').Select(Int32.Parse).ToList();
Upvotes: 19
Reputation: 16651
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 :)
Upvotes: 0
Reputation: 38430
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();
Upvotes: 45