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.

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top