开发者

Best way to take all querystring pairs and init a dictionary

I want to store all the key/value pairs in my querystring:

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

into a dictionary. Is there a quick way of doing开发者_运维知识库 this w/o having to manually cycle through all the items?


Try HttpUtility.ParseQueryString().

It gives you back a NameValueCollection of your keys and values.


Get the string that is found after the question mark, split the string on the '&' character. Then, for each string that is being returned, split again on the '=' character.

You could 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;

    }

}

Something like that. Remember, it is not safe, as it does not handle each edge-case. (For instance, given a string that has nothing after the first question mark, etc...), but it should get you started.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜