Menu

C# Query String Builder

August 7, 2013 - .NET / C#, ASP.NET MVC, Geek Bits, Web APIs, Web Stuff
C# Query String Builder

Here is a nice little extension method for building your query strings in C#


public static string ToQueryString(this NameValueCollection source, bool removeEmptyEntries)
{
    return source != null ? "?" + String.Join("&", source.AllKeys
        .Where(key => !removeEmptyEntries || source.GetValues(key).Any(value => !String.IsNullOrEmpty(value)))
        .SelectMany(key => source.GetValues(key)
            .Where(value => !removeEmptyEntries || !String.IsNullOrEmpty(value))
            .Select(value => String.Format("{0}={1}", HttpUtility.UrlEncode(key), value != null ? HttpUtility.UrlEncode(value) : string.Empty)))
        .ToArray())
        : string.Empty;
}

Share

Leave a Reply

Your email address will not be published. Required fields are marked *

*