Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to parse "querystring" formatted data

With the following code:

string q = "userID=16555&gameID=60&score=4542.122&time=343114"; 

What would be the easiest way to parse the values, preferably without writing my own parser? I'm looking for something with the same functionality as Request.querystring["gameID"].

like image 971
Tom Gullen Avatar asked Aug 14 '12 16:08

Tom Gullen


Video Answer


2 Answers

Pretty easy... Use the HttpUtility.ParseQueryString method.

Untested, but this should work:

var qs = "userID=16555&gameID=60&score=4542.122&time=343114"; var parsed = HttpUtility.ParseQueryString(qs); var userId = parsed["userID"];  //  ^^^^^^ Should be "16555".  Note this will be a string of course. 
like image 105
Chris Shain Avatar answered Oct 21 '22 02:10

Chris Shain


You can do it with linq like this.

string query = "id=3123123&userId=44423&format=json";  Dictionary<string,string> dicQueryString =          query.Split('&')              .ToDictionary(c => c.Split('=')[0],                            c => Uri.UnescapeDataString(c.Split('=')[1]));  string userId = dicQueryString["userID"]; 

Edit

If you can use HttpUtility.ParseQueryString then it will be a lot more straight forward and it wont be case-sensitive as in case of LinQ.

like image 43
Adil Avatar answered Oct 21 '22 03:10

Adil