Changing the querystring in an Uri

Here's a nice little fluent extension method that changes a querystring parameter in an Uri.

static class UriExtensions  
{
    public static Uri WithQueryStringParameter(
        this Uri uri, 
        string key, 
        string value)
    {
        string encodedKey = HttpUtility.UrlEncode(key);
        string encodedValue = HttpUtility.UrlEncode(value);
        string[] parameters = uri.Query.TrimStart('?').Split('&');
        IEnumerable<string> allButKey = parameters.Where(
            x => !x.StartsWith(
                encodedKey + "=",
                StringComparison.OrdinalIgnoreCase)
                );
        IEnumerable<string> withNewParam = allButKey.Concat(
            new[] { encodedKey + "=" + encodedValue }
            );
        string query = string.Join("&", withNewParam.ToArray());
        return new Uri(uri.GetLeftPart(UriPartial.Path) + "?" + query);
    }
}
Google
m@kli.dk @klinkby RSS feed  GitHub