Let\'s say I have a web page that currently accepts a single ID value via a url parameter:
http://example.com/mypage.aspx?ID=1234
I want to change it to acce
List<int> convertIDs = new List<int>;
string[] splitIds = ids.split(',');
foreach(string s in splitIds)
{
convertIDs.Add(int.Parse(s));
}
For completeness you will want to put try/catches around the for loop (or around the int.Parse() call) and handle the error based on your requirements. You can also do a tryparse() like so:
List<int> convertIDs = new List<int>;
string[] splitIds = ids.split(',');
foreach(string s in splitIds)
{
int i;
int.TryParse(out i);
if (i != 0)
convertIDs.Add(i);
}
Final code snippet that takes what I hope is the best from all the suggestions:
Function GetIDs(ByVal IDList As String) As List(Of Integer)
Dim SplitIDs() As String = IDList.Split(new Char() {","c}, StringSplitOptions.RemoveEmptyEntries)
GetIDs = new List(Of Integer)(SplitIDs.Length)
Dim CurID As Integer
For Each id As String In SplitIDs
If Integer.TryParse(id, CurID) Then GetIDs.Add(CurID)
Next id
End Function
I was hoping to be able to do it in one or two lines of code inline. One line to create the string array and hopefully find something in the framework I didn't already know to handle importing it to a List<int> that could handle the cast intelligently. But if I must move it to a method then I will. And yes, I'm using VB. I just prefer C# for asking questions because they'll get a larger audience and I'm just about as fluent.
You can instantiate a List<T> from an array.
VB.NET:
Dim lstIDs as new List(of Integer)(ids.split(','))
This is prone to casting errors though if the array contains non-int elements
To continue on previous answer, quite simply iterating through the array returned by Split and converting to a new array of ints. This sample below in C#:
string[] splitIds = stringIds.Split(',');
int[] ids = new int[splitIds.Length];
for (int i = 0; i < ids.Length; i++) {
ids[i] = Int32.Parse(splitIds[i]);
}
split is the first thing that comes to mind, but that returns an array, not a List; you could try something like:
List<int> intList = new List<int>;
foreach (string tempString in ids.split(',')
{
intList.add (convert.int32(tempString));
}
You can use string.Split() to split the values once you have extracted them from the URL.
string[] splitIds = ids.split(',');