title: Parse URL array parameters into C# Dictionaries
body: <p>I have the following code to parse key value pairs from URLs:</p>
  
  <pre><code>    public static NameValueCollection ParseQueryString(String query)
      {
          NameValueCollection queryParameters = new NameValueCollection();
          string[] querySegments = query.Split('&amp;');
          foreach (string segment in querySegments)
          {
              string[] parts = segment.Split('=');
              if (parts.Length &gt; 0)
              {
                  string key = parts[0].Trim(new char[] { '?', ' ' });
                  string val = parts[1].Trim();
  
                  queryParameters.Add(key, val);
              }
          }
  
          return queryParameters;
      }
  </code></pre>
  
  <p>I am using this function like this:</p>
  
  <pre><code>args = ParseQueryString("alpha=1&amp;beta=bbbb&amp;array%5B0%5D%5Ba%5D=1&amp;array%5B0%5D%5Bb%5D=2&amp;array%5B1%5D%5Ba%5D=1&amp;array%5B1%5D%5Bb%5D=2&amp;array%5B%5D=3&amp;array%5B%5D=4");
  foreach (var k in args.AllKeys)
  {
      tw.WriteLine(k + ": " + args[k]);
  }
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>alpha: 1
  beta: bbbb
  array[0][a]: 1
  array[0][b]: 2
  array[1][a]: 1
  array[1][b]: 2
  array[]: 3,4
  </code></pre>
  
  <p>I need an output of nested NameValueCollections or nested Dictionaries, so I can access the values somethis like this:</p>
  
  <pre><code>args = ParseQueryString("alpha=1&amp;beta=bbbb&amp;array%5B0%5D%5Ba%5D=1&amp;array%5B0%5D%5Bb%5D=2&amp;array%5B1%5D%5Ba%5D=1&amp;array%5B1%5D%5Bb%5D=2&amp;array%5B%5D=3&amp;array%5B%5D=4");
  var item = args.Get("array").Get(0).Get("b"); // will be "2"
  </code></pre>
  
  <p>What is the most elegant method to achieve this? I would prefer a solution without System.Web or any extra reference.</p>