How to remove or update part of query string in asp.net
<p>I have following querystring &amp; i want to remove or update part of querystring </p>

<p><code>?language=en-us&amp;issue=5&amp;pageid=18&amp;search=hawaii&amp;search=hawaii</code> // this is what i need to format</p>

<p>Problem is i have duplicate querystring for search key.</p>

<p>I tried following code but it is not working </p>

<pre><code>public static string RemoveQueryStringByKey(string url, string key)
{
    var uri = new Uri(url);

    // this gets all the query string key value pairs as a collection
    var newQueryString = HttpUtility.ParseQueryString(uri.Query);

    // this removes the key if exists
    newQueryString.Remove(key);

    // this gets the page path from root without QueryString
    string pagePathWithoutQueryString = uri.GetLeftPart(UriPartial.Path);

    return newQueryString.Count &gt; 0
        ? "{0}?{1}".FormatWith(pagePathWithoutQueryString, newQueryString)
        : pagePathWithoutQueryString;
}
</code></pre>

<p>FormatWith generates error</p>

<pre><code>string' does not contain a definition for 'FormatWith' and no extension method 'FormatWith' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?
</code></pre>

<p><strong>WORKING CODE:</strong></p>

<pre><code>public static string RemoveQueryStringByKey(string url, string key)
{
    var uri = new Uri(url);

    // this gets all the query string key value pairs as a collection
    var newQueryString = HttpUtility.ParseQueryString(uri.Query);

    // this removes the key if exists
    newQueryString.Remove(key);

    // this gets the page path from root without QueryString
    string pagePathWithoutQueryString = uri.GetLeftPart(UriPartial.Path);

    return newQueryString.Count &gt; 0
        ? string.Format("{0}?{1}", pagePathWithoutQueryString, newQueryString)
        : pagePathWithoutQueryString;
}
</code></pre>

<p>Function Call</p>

<pre><code>var URL = Request.Url.AbsoluteUri;
var uri = new Uri(Helper.RemoveQueryStringByKey(URL, "search"));
</code></pre>

<p>In my actual logic i have to check if QueryString <code>search</code> is present if it is then i remove it and replace it with the new search keyword.</p>

<p>You can apply it as per logic, &amp; the first example code which was not working was due to <code>FormatWith</code> which i was not able to fix so i used solution provide by <code>Oded</code> which works for me.</p>
