2

I have the following code to parse key value pairs from URLs:

    public static NameValueCollection ParseQueryString(String query)
    {
        NameValueCollection queryParameters = new NameValueCollection();
        string[] querySegments = query.Split('&');
        foreach (string segment in querySegments)
        {
            string[] parts = segment.Split('=');
            if (parts.Length > 0)
            {
                string key = parts[0].Trim(new char[] { '?', ' ' });
                string val = parts[1].Trim();

                queryParameters.Add(key, val);
            }
        }

        return queryParameters;
    }

I am using this function like this:

args = ParseQueryString("alpha=1&beta=bbbb&array%5B0%5D%5Ba%5D=1&array%5B0%5D%5Bb%5D=2&array%5B1%5D%5Ba%5D=1&array%5B1%5D%5Bb%5D=2&array%5B%5D=3&array%5B%5D=4");
foreach (var k in args.AllKeys)
{
    tw.WriteLine(k + ": " + args[k]);
}

Output:

alpha: 1
beta: bbbb
array[0][a]: 1
array[0][b]: 2
array[1][a]: 1
array[1][b]: 2
array[]: 3,4

I need an output of nested NameValueCollections or nested Dictionaries, so I can access the values somethis like this:

args = ParseQueryString("alpha=1&beta=bbbb&array%5B0%5D%5Ba%5D=1&array%5B0%5D%5Bb%5D=2&array%5B1%5D%5Ba%5D=1&array%5B1%5D%5Bb%5D=2&array%5B%5D=3&array%5B%5D=4");
var item = args.Get("array").Get(0).Get("b"); // will be "2"

What is the most elegant method to achieve this? I would prefer a solution without System.Web or any extra reference.

brnbs
  • 75
  • 6
  • I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackoverflow.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders May 15 '14 at 19:25
  • 1
    Not using libraries designed specifically for a task is usually a way of making life needlessly difficult for yourself – Ben Aaronson May 15 '14 at 19:26
  • possible duplicate of [Get url parameters from a string in .NET](http://stackoverflow.com/questions/659887/get-url-parameters-from-a-string-in-net) – Chris Hinton May 15 '14 at 19:32
  • 1
    @BenAaronson You're right, but I wanted my app to be compatible with 4.0 client profile. Anyway I would be happy with a System.Web solution too! – brnbs May 15 '14 at 19:32
  • @cahinton I have seen that question, there is no mention about arrays encoded in the query string. – brnbs May 15 '14 at 19:35

1 Answers1

0

If you use the ASP.NET MVC Framework, the default MVC parameter binder can deal with it automatically in the following way:

// GetData?filters[0][field]=fieldName&filters[0][type]=number&filters[0][value]=3
public ActionResult GetData(IEnumerable<Dictionary<string,string>> filters) 
{
    // todo
}

For more info and examples check out this blog post that I wrote on this topic.

Darkseal
  • 9,205
  • 8
  • 78
  • 111