The best way to take all querystring pairs and run the dictionary

I want to save all key / value pairs in my line:

www.example.com/?a=2&b=3&c=34

to the dictionary. Is there a quick way to do this without having to manually iterate over all the elements?

+5
source share
2 answers

Give it a try HttpUtility.ParseQueryString().

It returns you NameValueCollectionyour keys and values.

+13
source

Get the string found after the question mark, divide the string by the '&' character. Then, for each returned string, separate the "=" character again.

You can even create an extension method for it.

public static class StringExtensions
{

    public Dictionary<string, string> ExtractQueryStringValues( this string target )
    {

        string queryString = target.Split (target.IndexOf ('?') + 1);

        string[] keyvaluePairs = queryString.Split ('&');

        Dictionary<string, string> result = new Dictionary<string, string>();

        foreach( string pair in keyvaluePairs )
        {
             var tmp = pair.Split ('=');

             result.Add (tmp[0], tmp[1]);
        }

        return result;

    }

}

- . , , . (, , ..), .

0

All Articles