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 see my answer came rather late, i.e. several other had written the same. Therefore I present an alternative method using regular expressions to validate and divide the string.
class Program
{
//Accepts one or more groups of one or more digits, separated by commas.
private static readonly Regex CSStringPattern = new Regex(@"^(\d+,?)*\d+$");
//A single ID inside the string. Must only be used after validation
private static readonly Regex SingleIdPattern = new Regex(@"\d+");
static void Main(string[] args)
{
string queryString = "1234,4321,6789";
int[] ids = ConvertCommaSeparatedStringToIntArray(queryString);
}
private static int[] ConvertCommaSeparatedStringToIntArray(string csString)
{
if (!CSStringPattern.IsMatch(csString))
throw new FormatException(string.Format("Invalid comma separated string '{0}'",
csString));
List ids = new List();
foreach (Match match in SingleIdPattern.Matches(csString))
{
ids.Add(int.Parse(match.Value)); //No need to TryParse since string has been validated
}
return ids.ToArray();
}
}