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
I think the easiest way is to split as shown before, and then loop through the values and try to convert to int.
class Program
{
static void Main(string[] args)
{
string queryString = "1234,4321,6789";
int[] ids = ConvertCommaSeparatedStringToIntArray(queryString);
}
private static int[] ConvertCommaSeparatedStringToIntArray(string csString)
{
//splitting string to substrings
string[] idStrings = csString.Split(',');
//initializing int-array of same length
int[] ids = new int[idStrings.Length];
//looping all substrings
for (int i = 0; i < idStrings.Length; i++)
{
string idString = idStrings[i];
//trying to convert one substring to int
int id;
if (!int.TryParse(idString, out id))
throw new FormatException(String.Format("Query string contained malformed id '{0}'", idString));
//writing value back to the int-array
ids[i] = id;
}
return ids;
}
}