<p>Let's say I have a web page that currently accepts a single ID value via a url parameter:<br>
    <a href="http://example.com/mypage.aspx?ID=1234" rel="nofollow noreferrer">http://example.com/mypage.aspx?ID=1234</a></p>

<p>I want to change it to accept a <em>list</em> of ids, like this:<br>
    <a href="http://example.com/mypage.aspx?IDs=1234,4321,6789" rel="nofollow noreferrer">http://example.com/mypage.aspx?IDs=1234,4321,6789</a></p>

<p>So it's available to my code as a string via <em>context.Request.QueryString["IDs"].</em>  What's the best way to turn that string value into a List&lt;int>?</p>

<p><strong>Edit:</strong> I know how to do .split() on a comma to get a list of strings, but I ask because I don't know how to easily convert that string list to an int list.  This is still in .Net 2.0, so no lambdas.</p>

[{'answer_id': 63472, 'author': 'Grokys', 'author_id': 6448, 'author_profile': 'https://Stackoverflow.com/users/6448', 'pm_score': 0, 'selected': False, 'text': "<p>You can use string.Split() to split the values once you have extracted them from the URL.</p>\n\n<pre><code>string[] splitIds = ids.split(',');\n</code></pre>\n"}, {'answer_id': 63508, 'author': 'Mark Embling', 'author_id': 6844, 'author_profile': 'https://Stackoverflow.com/users/6844', 'pm_score': 2, 'selected': False, 'text': "<p>All I can think of is to loop over the list of strings (which you have got from performing a split) and doing something like <code>int.TryParse()</code> on them one after the other and putting them into a new <code>List&lt;int&gt;</code>. Encapsulate it in a nice little helper method somewhere and it won't be too horrid.</p>\n"}, {'answer_id': 63521, 'author': 'sirrocco', 'author_id': 5246, 'author_profile': 'https://Stackoverflow.com/users/5246', 'pm_score': 0, 'selected': False, 'text': "<p>You'll just have to foreach through them and int.TryParse each one of them. after that just add to the list.</p>\n\n<p>Nevermind - @Splash beat me to it</p>\n"}, {'answer_id': 63527, 'author': 'user7658', 'author_id': 7658, 'author_profile': 'https://Stackoverflow.com/users/7658', 'pm_score': 2, 'selected': False, 'text': "<p>You can instantiate a List&lt;T&gt; from an array.</p>\n\n<p>VB.NET:</p>\n\n<pre><code>Dim lstIDs as new List(of Integer)(ids.split(','))\n</code></pre>\n\n<p>This is prone to casting errors though if the array contains non-int elements</p>\n"}, {'answer_id': 63544, 'author': 'Richard C', 'author_id': 6389, 'author_profile': 'https://Stackoverflow.com/users/6389', 'pm_score': 1, 'selected': False, 'text': "<p>split is the first thing that comes to mind, but that returns an array, not a List;\nyou could try something like:</p>\n\n<pre><code>\nList&lt;int&gt; intList = new List&lt;int&gt;;\n\nforeach (string tempString in ids.split(',')\n{\n    intList.add (convert.int32(tempString));\n}\n\n</code></pre>\n"}, {'answer_id': 63561, 'author': 'Compile This', 'author_id': 4048, 'author_profile': 'https://Stackoverflow.com/users/4048', 'pm_score': 4, 'selected': False, 'text': '<p>Something like this might work:</p>\n\n<pre><code>public static IList&lt;int&gt; GetIdListFromString(string idList)\n{\n    string[] values = idList.Split(\',\');\n\n    List&lt;int&gt; ids = new List&lt;int&gt;(values.Length);\n\n    foreach (string s in values)\n    {\n        int i;\n\n        if (int.TryParse(s, out i))\n        {\n            ids.Add(i);\n        }\n    }\n\n    return ids;\n}\n</code></pre>\n\n<p>Which would then be used:</p>\n\n<pre><code>string intString = "1234,4321,6789";\n\nIList&lt;int&gt; list = GetIdListFromString(intString);\n\nforeach (int i in list)\n{\n    Console.WriteLine(i);\n}\n</code></pre>\n'}, {'answer_id': 63578, 'author': 'dpollock', 'author_id': 7884, 'author_profile': 'https://Stackoverflow.com/users/7884', 'pm_score': 0, 'selected': False, 'text': "<pre><code>List&lt;int&gt; convertIDs = new List&lt;int&gt;;\nstring[] splitIds = ids.split(',');\nforeach(string s in splitIds)\n{\n    convertIDs.Add(int.Parse(s));\n}\n</code></pre>\n\n<p>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:</p>\n\n<pre><code>List&lt;int&gt; convertIDs = new List&lt;int&gt;;\nstring[] splitIds = ids.split(',');\nforeach(string s in splitIds)\n{\n    int i;\n    int.TryParse(out i);\n    if (i != 0)\n       convertIDs.Add(i);\n}\n</code></pre>\n"}, {'answer_id': 63584, 'author': 'Philibert Perusse', 'author_id': 7984, 'author_profile': 'https://Stackoverflow.com/users/7984', 'pm_score': 0, 'selected': False, 'text': "<p>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#:</p>\n\n<pre><code>        string[] splitIds = stringIds.Split(',');\n\n        int[] ids = new int[splitIds.Length];\n        for (int i = 0; i &lt; ids.Length; i++) {\n            ids[i] = Int32.Parse(splitIds[i]);\n        }\n</code></pre>\n"}, {'answer_id': 63601, 'author': 'Jesse Millikan', 'author_id': 7526, 'author_profile': 'https://Stackoverflow.com/users/7526', 'pm_score': 2, 'selected': False, 'text': '<p>If you like the functional style, you can try something like</p>\n\n<pre><code>    string ids = "1,2,3,4,5";\n\n    List&lt;int&gt; l = new List&lt;int&gt;(Array.ConvertAll(\n        ids.Split(\',\'), new Converter&lt;string, int&gt;(int.Parse)));\n</code></pre>\n\n<p>No lambdas, but you do have Converters and Predicates and other nice things that can be made from methods.</p>\n'}, {'answer_id': 63649, 'author': 'Magnus Akselvoll', 'author_id': 4683, 'author_profile': 'https://Stackoverflow.com/users/4683', 'pm_score': 0, 'selected': False, 'text': '<p>I think the easiest way is to split as shown before, and then loop through the values and try to convert to int.</p>\n\n<pre><code>class Program\n{\n    static void Main(string[] args)\n    {\n        string queryString = "1234,4321,6789";\n\n        int[] ids = ConvertCommaSeparatedStringToIntArray(queryString);\n    }\n\n    private static int[] ConvertCommaSeparatedStringToIntArray(string csString)\n    {\n        //splitting string to substrings\n        string[] idStrings = csString.Split(\',\');\n\n        //initializing int-array of same length\n        int[] ids = new int[idStrings.Length];\n\n        //looping all substrings\n        for (int i = 0; i &lt; idStrings.Length; i++)\n        {\n            string idString = idStrings[i];\n\n            //trying to convert one substring to int\n            int id;\n            if (!int.TryParse(idString, out id))\n                throw new FormatException(String.Format("Query string contained malformed id \'{0}\'", idString));\n\n            //writing value back to the int-array\n            ids[i] = id;\n        }\n\n        return ids;\n    }\n}\n</code></pre>\n'}, {'answer_id': 63654, 'author': 'Ovid', 'author_id': 8003, 'author_profile': 'https://Stackoverflow.com/users/8003', 'pm_score': 5, 'selected': True, 'text': '<p>No offense to those who provided clear answers, but many people seem to be answering your question instead of addressing your problem.  You want multiple IDs, so you think you could this this:</p>\n\n<p><a href="http://example.com/mypage.aspx?IDs=1234,4321,6789" rel="noreferrer">http://example.com/mypage.aspx?IDs=1234,4321,6789</a></p>\n\n<p>The problem is that this is a non-robust solution. In the future, if you want multiple values, what do you do if they have commas?  A better solution (and this is perfectly valid in a query string), is to use multiple parameters with the same name:</p>\n\n<p><a href="http://example.com/mypage.aspx?ID=1234;ID=4321;ID=6789" rel="noreferrer">http://example.com/mypage.aspx?ID=1234;ID=4321;ID=6789</a></p>\n\n<p>Then, whatever query string parser you use should be able to return a list of IDs.  If it can\'t handle this (and also handle semi-colons instead of ampersands), then it\'s broken.</p>\n'}, {'answer_id': 63686, 'author': 'Joel Coehoorn', 'author_id': 3043, 'author_profile': 'https://Stackoverflow.com/users/3043', 'pm_score': 1, 'selected': False, 'text': '<p>Final code snippet that takes what I hope is the best from all the suggestions:</p>\n\n<pre><code>Function GetIDs(ByVal IDList As String) As List(Of Integer)\n    Dim SplitIDs() As String = IDList.Split(new Char() {","c}, StringSplitOptions.RemoveEmptyEntries)\n    GetIDs = new List(Of Integer)(SplitIDs.Length)\n    Dim CurID As Integer\n    For Each id As String In SplitIDs\n        If Integer.TryParse(id, CurID) Then GetIDs.Add(CurID)\n    Next id\nEnd Function\n</code></pre>\n\n<p>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&lt;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.</p>\n'}, {'answer_id': 63836, 'author': 'Magnus Akselvoll', 'author_id': 4683, 'author_profile': 'https://Stackoverflow.com/users/4683', 'pm_score': 2, 'selected': False, 'text': '<p>I see <a href="https://stackoverflow.com/questions/63463/split-out-ints-from-string#63649">my answer</a> 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.</p>\n\n<pre><code>class Program\n{\n    //Accepts one or more groups of one or more digits, separated by commas.\n    private static readonly Regex CSStringPattern = new Regex(@"^(\\d+,?)*\\d+$");\n\n    //A single ID inside the string. Must only be used after validation\n    private static readonly Regex SingleIdPattern = new Regex(@"\\d+");\n\n    static void Main(string[] args)\n    {\n        string queryString = "1234,4321,6789";\n\n        int[] ids = ConvertCommaSeparatedStringToIntArray(queryString);\n    }\n\n    private static int[] ConvertCommaSeparatedStringToIntArray(string csString)\n    {\n        if (!CSStringPattern.IsMatch(csString))\n            throw new FormatException(string.Format("Invalid comma separated string \'{0}\'",\n                                                    csString));\n\n        List&lt;int&gt; ids = new List&lt;int&gt;();\n        foreach (Match match in SingleIdPattern.Matches(csString))\n        {\n            ids.Add(int.Parse(match.Value)); //No need to TryParse since string has been validated\n        }\n        return ids.ToArray();\n    }\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/63463', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3043/']