Lee Kelleher’s Weblog

Just another WordPress.com weblog

How to convert NameValueCollection to a (Query) String

with 5 comments

Most ASP.NET developers know that you can get a key/value pair string from the Request.QueryString object (via the .ToString() method). However that functionality isn’t the same for a generic NameValueCollection object (of which Request.QueryString is derived from).

So how do you take a NameValueCollection object and get a nicely formatted key/value pair string? (i.e. “key1=value1&key2=value2“) … Here’s a method I wrote a while ago:

/// <summary>
/// Constructs a QueryString (string).
/// Consider this method to be the opposite of "System.Web.HttpUtility.ParseQueryString"
/// </summary>
/// <param name="nvc">NameValueCollection</param>
/// <returns>String</returns>
public static String ConstructQueryString(NameValueCollection parameters)
{
	List<String> items = new List<String>();

	foreach (String name in parameters)
		items.Add(String.Concat(name, "=", System.Web.HttpUtility.UrlEncode(parameters[name])));

	return String.Join("&", items.ToArray());
}

Just in case you didn’t know about the System.Web.HttpUtility.ParseQueryString method, it’s a quick way of converting a query (key/value pairs) string back into a NameValueCollection.

Written by Lee Kelleher

June 6, 2008 at 1:22 pm

Posted in blog

Tagged with , , , ,

5 Responses to 'How to convert NameValueCollection to a (Query) String'

Subscribe to comments with RSS or TrackBack to 'How to convert NameValueCollection to a (Query) String'.

  1. don’t you mean foreach(string name in parameters.Keys ) ?

    Ross

    6 Jun 08 at 2:58 pm

  2. Wow I take it back, 6 years and I never noticed that you don’t need the .Keys on a NV collection. :(

    Ross

    6 Jun 08 at 3:01 pm

  3. Fair point… and “parameters.Keys” does make more sense really.

    Lee Kelleher

    6 Jun 08 at 3:24 pm

  4. Thanks for that! Nice neat method…. Been searching for an easy to use URL encoding facility in .NET.
    And the icing on the cake is that I didn’t even know about the String.Join method - that’s gonna get used time and time again.

    Cheers!

    Chris

    4 Jul 08 at 7:45 pm

  5. Cheers Chris, glad I could help. :-D

    Lee Kelleher

    7 Jul 08 at 8:48 pm

Leave a Reply