<p>I would like to parse a string such as <code>p1=6&amp;p2=7&amp;p3=8</code> into a <code>NameValueCollection</code>.</p>

<p>What is the most elegant way of doing this when you don't have access to the <code>Page.Request</code> object?</p>

[{'answer_id': 68639, 'author': 'Mark Glorie', 'author_id': 952, 'author_profile': 'https://Stackoverflow.com/users/952', 'pm_score': 0, 'selected': False, 'text': '<p>Hit up Request.QueryString.Keys for a NameValueCollection of all query string parameters.</p>\n'}, {'answer_id': 68644, 'author': 'Mike Becatti', 'author_id': 6617, 'author_profile': 'https://Stackoverflow.com/users/6617', 'pm_score': 1, 'selected': False, 'text': '<p>Just access Request.QueryString. AllKeys mentioned as another answer just gets you an array of keys.  </p>\n'}, {'answer_id': 68648, 'author': 'Guy Starbuck', 'author_id': 2194, 'author_profile': 'https://Stackoverflow.com/users/2194', 'pm_score': 10, 'selected': True, 'text': '<p>There\'s a built-in .NET utility for this:  <a href="http://msdn.microsoft.com/en-us/library/ms150046.aspx" rel="noreferrer">HttpUtility.ParseQueryString</a></p>\n\n<pre class="lang-cs prettyprint-override"><code>// C#\nNameValueCollection qscoll = HttpUtility.ParseQueryString(querystring);\n</code></pre>\n\n<pre class="lang-vb prettyprint-override"><code>\' VB.NET\nDim qscoll As NameValueCollection = HttpUtility.ParseQueryString(querystring)\n</code></pre>\n\n<p>You may need to replace <code>querystring</code> with <code>new Uri(fullUrl).Query</code>.</p>\n'}, {'answer_id': 68733, 'author': 'rp.', 'author_id': 2536, 'author_profile': 'https://Stackoverflow.com/users/2536', 'pm_score': 2, 'selected': False, 'text': '<pre><code>    private void button1_Click( object sender, EventArgs e )\n    {\n        string s = @"p1=6&amp;p2=7&amp;p3=8";\n        NameValueCollection nvc = new NameValueCollection();\n\n        foreach ( string vp in Regex.Split( s, "&amp;" ) )\n        {\n            string[] singlePair = Regex.Split( vp, "=" );\n            if ( singlePair.Length == 2 )\n            {\n                nvc.Add( singlePair[ 0 ], singlePair[ 1 ] );    \n            }    \n        }\n    }\n</code></pre>\n'}, {'answer_id': 68803, 'author': 'Scott Dorman', 'author_id': 1559, 'author_profile': 'https://Stackoverflow.com/users/1559', 'pm_score': 6, 'selected': False, 'text': "<p>HttpUtility.ParseQueryString will work as long as you are in a web app or don't mind including a dependency on System.Web. Another way to do this is:</p>\n\n<pre><code>NameValueCollection queryParameters = new NameValueCollection();\nstring[] querySegments = queryString.Split('&amp;');\nforeach(string segment in querySegments)\n{\n   string[] parts = segment.Split('=');\n   if (parts.Length &gt; 0)\n   {\n      string key = parts[0].Trim(new char[] { '?', ' ' });\n      string val = parts[1].Trim();\n\n      queryParameters.Add(key, val);\n   }\n}\n</code></pre>\n"}, {'answer_id': 1322960, 'author': 'densom', 'author_id': 158581, 'author_profile': 'https://Stackoverflow.com/users/158581', 'pm_score': 4, 'selected': False, 'text': '<p>I wanted to remove the dependency on System.Web so that I could parse the query string of a ClickOnce deployment, while having the prerequisites limited to the "Client-only Framework Subset".</p>\n\n<p>I liked rp\'s answer.  I added some additional logic.</p>\n\n<pre><code>public static NameValueCollection ParseQueryString(string s)\n    {\n        NameValueCollection nvc = new NameValueCollection();\n\n        // remove anything other than query string from url\n        if(s.Contains("?"))\n        {\n            s = s.Substring(s.IndexOf(\'?\') + 1);\n        }\n\n        foreach (string vp in Regex.Split(s, "&amp;"))\n        {\n            string[] singlePair = Regex.Split(vp, "=");\n            if (singlePair.Length == 2)\n            {\n                nvc.Add(singlePair[0], singlePair[1]);\n            }\n            else\n            {\n                // only one key with no value specified in query string\n                nvc.Add(singlePair[0], string.Empty);\n            }\n        }\n\n        return nvc;\n    }\n</code></pre>\n'}, {'answer_id': 8169365, 'author': 'alex1kirch', 'author_id': 991442, 'author_profile': 'https://Stackoverflow.com/users/991442', 'pm_score': 1, 'selected': False, 'text': '<p><code>HttpUtility.ParseQueryString(Request.Url.Query)</code> return is <code>HttpValueCollection</code> (internal class). It inherits from <code>NameValueCollection</code>.</p>\n\n<pre><code>    var qs = HttpUtility.ParseQueryString(Request.Url.Query);\n    qs.Remove("foo"); \n\n    string url = "~/Default.aspx"; \n    if (qs.Count &gt; 0)\n       url = url + "?" + qs.ToString();\n\n    Response.Redirect(url); \n</code></pre>\n'}, {'answer_id': 16565615, 'author': 'Josh Brown', 'author_id': 341536, 'author_profile': 'https://Stackoverflow.com/users/341536', 'pm_score': 3, 'selected': False, 'text': '<p>I needed a function that is a little more versatile than what was provided already when working with OLSC queries.</p>\n\n<ul>\n<li>Values may contain multiple equal signs</li>\n<li>Decode encoded characters in both name and value</li>\n<li>Capable of running on Client Framework</li>\n<li>Capable of running on Mobile Framework.</li>\n</ul>\n\n<p>Here is my solution:</p>\n\n<pre><code>Public Shared Function ParseQueryString(ByVal uri As Uri) As System.Collections.Specialized.NameValueCollection\n    Dim result = New System.Collections.Specialized.NameValueCollection(4)\n    Dim query = uri.Query\n    If Not String.IsNullOrEmpty(query) Then\n        Dim pairs = query.Substring(1).Split("&amp;"c)\n        For Each pair In pairs\n            Dim parts = pair.Split({"="c}, 2)\n\n            Dim name = System.Uri.UnescapeDataString(parts(0))\n            Dim value = If(parts.Length = 1, String.Empty,\n                System.Uri.UnescapeDataString(parts(1)))\n\n            result.Add(name, value)\n        Next\n    End If\n    Return result\nEnd Function\n</code></pre>\n\n<p>It may not be a bad idea to tack <code>&lt;Extension()&gt;</code> on that too to add the capability to Uri itself.</p>\n'}, {'answer_id': 19893289, 'author': 'Farhawd', 'author_id': 998276, 'author_profile': 'https://Stackoverflow.com/users/998276', 'pm_score': -1, 'selected': False, 'text': '<p>This is my code, I think it\'s very useful: </p>\n\n<pre><code>public String GetQueryString(string ItemToRemoveOrInsert = null, string InsertValue = null )\n{\n    System.Collections.Specialized.NameValueCollection filtered = new System.Collections.Specialized.NameValueCollection(Request.QueryString);\n    if (ItemToRemoveOrInsert != null)\n    {\n        filtered.Remove(ItemToRemoveOrInsert);\n        if (!string.IsNullOrWhiteSpace(InsertValue))\n        {\n            filtered.Add(ItemToRemoveOrInsert, InsertValue);\n        }\n    }\n\n    string StrQr = string.Join("&amp;", filtered.AllKeys.Select(key =&gt; key + "=" + filtered[key]).ToArray());\n    if (!string.IsNullOrWhiteSpace(StrQr)){\n        StrQr="?" + StrQr;\n    }\n\n    return StrQr;\n}\n</code></pre>\n'}, {'answer_id': 21309603, 'author': 'Tiele Declercq', 'author_id': 1683154, 'author_profile': 'https://Stackoverflow.com/users/1683154', 'pm_score': 1, 'selected': False, 'text': '<p>Since everyone seems to be pasting his solution.. here\'s mine :-)\nI needed this from within a class library without <code>System.Web</code> to fetch id parameters from stored hyperlinks.</p>\n\n<p>Thought I\'d share because I find this solution faster and better looking.</p>\n\n<pre><code>public static class Statics\n    public static Dictionary&lt;string, string&gt; QueryParse(string url)\n    {\n        Dictionary&lt;string, string&gt; qDict = new Dictionary&lt;string, string&gt;();\n        foreach (string qPair in url.Substring(url.IndexOf(\'?\') + 1).Split(\'&amp;\'))\n        {\n            string[] qVal = qPair.Split(\'=\');\n            qDict.Add(qVal[0], Uri.UnescapeDataString(qVal[1]));\n        }\n        return qDict;\n    }\n\n    public static string QueryGet(string url, string param)\n    {\n        var qDict = QueryParse(url);\n        return qDict[param];\n    }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>Statics.QueryGet(url, "id")\n</code></pre>\n'}, {'answer_id': 22167748, 'author': 'James Skimming', 'author_id': 495964, 'author_profile': 'https://Stackoverflow.com/users/495964', 'pm_score': 5, 'selected': False, 'text': '<p>A lot of the answers are providing custom examples because of the accepted answer\'s dependency on <a href="http://msdn.microsoft.com/en-us/library/system.web.aspx" rel="noreferrer">System.Web</a>. From the <a href="http://www.nuget.org/packages/Microsoft.AspNet.WebApi.Client" rel="noreferrer">Microsoft.AspNet.WebApi.Client</a> NuGet package there is a <a href="http://msdn.microsoft.com/en-us/library/system.net.http.uriextensions.parsequerystring.aspx" rel="noreferrer">UriExtensions.ParseQueryString</a>, method that can also be used:</p>\n\n<pre><code>var uri = new Uri("https://stackoverflow.com/a/22167748?p1=6&amp;p2=7&amp;p3=8");\nNameValueCollection query = uri.ParseQueryString();\n</code></pre>\n\n<p>So if you want to avoid the <a href="http://msdn.microsoft.com/en-us/library/system.web.aspx" rel="noreferrer">System.Web</a> dependency and don\'t want to roll your own, this is a good option.</p>\n'}, {'answer_id': 24921357, 'author': 'Thomas Levesque', 'author_id': 98713, 'author_profile': 'https://Stackoverflow.com/users/98713', 'pm_score': 2, 'selected': False, 'text': '<p>I just realized that <a href="https://www.nuget.org/packages/Microsoft.AspNet.WebApi.Client/" rel="nofollow">Web API Client</a> has a <code>ParseQueryString</code> extension method that works on a <code>Uri</code> and returns a <code>HttpValueCollection</code>:</p>\n\n<pre><code>var parameters = uri.ParseQueryString();\nstring foo = parameters["foo"];\n</code></pre>\n'}, {'answer_id': 28693490, 'author': 'mirko cro 1234', 'author_id': 3386904, 'author_profile': 'https://Stackoverflow.com/users/3386904', 'pm_score': 0, 'selected': False, 'text': '<p>To get all Querystring values try this:</p>\n\n<pre><code>    Dim qscoll As NameValueCollection = HttpUtility.ParseQueryString(querystring)\n\nDim sb As New StringBuilder("&lt;br /&gt;")\nFor Each s As String In qscoll.AllKeys\n\n  Response.Write(s &amp; " - " &amp; qscoll(s) &amp; "&lt;br /&gt;")\n\nNext s\n</code></pre>\n'}, {'answer_id': 33224447, 'author': 'Jerod Venema', 'author_id': 25330, 'author_profile': 'https://Stackoverflow.com/users/25330', 'pm_score': 3, 'selected': False, 'text': '<p>To do this without <code>System.Web</code>, without writing it yourself, and without additional NuGet packages:</p>\n\n<ol>\n<li>Add a reference to <code>System.Net.Http.Formatting</code></li>\n<li>Add <code>using System.Net.Http;</code></li>\n<li><p>Use this code:</p>\n\n<pre><code>new Uri(uri).ParseQueryString()\n</code></pre></li>\n</ol>\n\n<p><a href="https://msdn.microsoft.com/en-us/library/system.net.http.uriextensions(v=vs.118).aspx" rel="nofollow noreferrer">https://msdn.microsoft.com/en-us/library/system.net.http.uriextensions(v=vs.118).aspx</a></p>\n'}, {'answer_id': 34920103, 'author': 'Hamit YILDIRIM', 'author_id': 914284, 'author_profile': 'https://Stackoverflow.com/users/914284', 'pm_score': 0, 'selected': False, 'text': '<pre><code>        var q = Request.QueryString;\n        NameValueCollection qscoll = HttpUtility.ParseQueryString(q.ToString());\n</code></pre>\n'}, {'answer_id': 38171014, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<h1>If you don\'t want the System.Web dependency, just paste this source code from HttpUtility class.</h1>\n\n<p>I just whipped this together from the source code of <a href="https://github.com/mono/mono/tree/master/mcs/class/System.Web" rel="nofollow">Mono</a>. It contains the HttpUtility and all it\'s dependencies (like IHtmlString, Helpers, HttpEncoder, HttpQSCollection).</p>\n\n<p><em>Then</em> use <code>HttpUtility.ParseQueryString</code>.</p>\n\n<p><a href="https://gist.github.com/bjorn-ali-goransson/b04a7c44808bb2de8cca3fc9a3762f9c" rel="nofollow">https://gist.github.com/bjorn-ali-goransson/b04a7c44808bb2de8cca3fc9a3762f9c</a></p>\n'}, {'answer_id': 39055664, 'author': 'elgoya', 'author_id': 1828356, 'author_profile': 'https://Stackoverflow.com/users/1828356', 'pm_score': -1, 'selected': False, 'text': '<p>I translate to C# version of josh-brown in VB</p>\n\n<pre><code>private System.Collections.Specialized.NameValueCollection ParseQueryString(Uri uri)\n{\n    var result = new System.Collections.Specialized.NameValueCollection(4);\n    var query = uri.Query;\n    if (!String.IsNullOrEmpty(query))\n    {\n        var pairs = query.Substring(1).Split("&amp;".ToCharArray());\n        foreach (var pair in pairs)\n        {\n            var parts = pair.Split("=".ToCharArray(), 2);\n            var name = System.Uri.UnescapeDataString(parts[0]);\n            var value = (parts.Length == 1) ? String.Empty : System.Uri.UnescapeDataString(parts[1]);\n            result.Add(name, value);\n        }\n    }\n    return result;\n}\n</code></pre>\n'}, {'answer_id': 45716527, 'author': 'Amadeus Sánchez', 'author_id': 1698964, 'author_profile': 'https://Stackoverflow.com/users/1698964', 'pm_score': 2, 'selected': False, 'text': '<p>If you want to avoid the dependency on System.Web that is required to use <a href="https://msdn.microsoft.com/en-us/library/ms150046.aspx" rel="nofollow noreferrer">HttpUtility.ParseQueryString</a>, you could use the <code>Uri</code> extension method <code>ParseQueryString</code> found in <code>System.Net.Http</code>.</p>\n\n<p>Make sure to add a reference (if you haven\'t already)  to <code>System.Net.Http</code> in your project.</p>\n\n<p>Note that you have to convert the response body to a valid <code>Uri</code> so that <code>ParseQueryString</code> (in <code>System.Net.Http</code>)works.</p>\n\n<pre><code>string body = "value1=randomvalue1&amp;value2=randomValue2";\n\n// "http://localhost/query?" is added to the string "body" in order to create a valid Uri.\nstring urlBody = "http://localhost/query?" + body;\nNameValueCollection coll = new Uri(urlBody).ParseQueryString();\n</code></pre>\n'}, {'answer_id': 61217955, 'author': 'Nahom Haile', 'author_id': 12178449, 'author_profile': 'https://Stackoverflow.com/users/12178449', 'pm_score': -1, 'selected': False, 'text': '<pre><code>let search = window.location.search;\n\nconsole.log(search);\n\nlet qString = search.substring(1);\n\nwhile(qString.indexOf("+") !== -1)\n\n   qString  = qString.replace("+", "");\n\nlet qArray = qString.split("&amp;");\n\nlet values = [];\n\nfor(let i = 0; i &lt; qArray.length; i++){\n   let pos = qArray[i].search("=");\n   let keyVal = qArray[i].substring(0, pos);\n   let dataVal = qArray[i].substring(pos + 1);\n   dataVal = decodeURIComponent(dataVal);\n   values[keyVal] = dataVal;\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/68624', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4998/']