Skip to content

Instantly share code, notes, and snippets.

@madd0
Created November 15, 2011 08:50
Show Gist options
  • Save madd0/1366487 to your computer and use it in GitHub Desktop.
Save madd0/1366487 to your computer and use it in GitHub Desktop.
Create a URL query string from a NameValueCollection in C#
var nvc = new NameValueCollection
{
{ "key1", "value1" },
{ "key2", "value2" },
{ "key3", "" }
};
var builder = new UriBuilder("http://www.example.com");
// Create query string with all values
builder.Query = string.Join("&", nvc.AllKeys.Select(key => string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(nvc[key]))));
// Omit empty values
builder.Query = string.Join("&", nvc.AllKeys.Where(key => !string.IsNullOrWhiteSpace(nvc[key])).Select(key => string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(nvc[key]))));
@theShiva
Copy link

Is there a way to do this without dependency on HttpUtility? I need something like this in a class library's Helper class.
Also, have you tried this with duplicate key names? NameValueCollection allows duplicate keys and another requirement of mine is that the NameValueCollection I have can contain duplicate keys.

@Valve
Copy link

Valve commented Nov 25, 2013

@theShiva, since .NET 4.5 you can use System.Net.WebUtility, which is in the System.dll assembly.

You can use this class in portable library or WinRT/Windows Phone

@mpilar
Copy link

mpilar commented Aug 14, 2014

I know this is old but I thought I would update with a version that takes multiple querystring values into account to be compliant with the RFC:

uri.Query = string.Join("&",
                    nvc.AllKeys.Where(key => !string.IsNullOrWhiteSpace(nvc[key]))
                        .Select(
                            key => string.Join("&", nvc.GetValues(key).Select(val => string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(val))))));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment