Adding or Replacing a Page item in a QueryString in C#. Can this code be improved?  I'm avoiding using the QueryString collection because the query string may contain eg: OrderBy=Column1&amp;OrderBy=Column2 and it didn't seem helpful to start with those switched into QueryString["OrderBy"]=="Column1,Column2";

    var query = "";
    if (urlHelper.RequestContext.HttpContext.Request.Url != null)
    {
        query = urlHelper.RequestContext.HttpContext.Request.Url.Query.TrimStart('?');
        if (query.Length &gt; 0)
        {
            var kvp =
                query.Split('&amp;').Select(x =&gt; x.Split('='))
                    .Select(x =&gt; new { Key = x[0], Value = (x.Length &gt; 0) ? x[1] : ""})
                    .Where(x =&gt; x.Key != "page")
                    .ToList();
            kvp.Add(new { Key = "page", Value = number.ToString() });
            query = String.Join("&amp;", kvp.Select(x =&gt; x.Key + "=" + x.Value).ToArray());
        }
        else query = String.Format("page={0}", number);
    }
I think that yes this code can be improved.

use a regular expression:

            var newQuery = Regex.Replace(currentQuery, @"(?i)(page=\d*&amp;?)", "").TrimEnd('&amp;');
            if (newQuery.Length &gt; 0)
                newQuery += string.Format("&amp;Page={0}", currentPageNo);
            else
                newQuery = string.Format("Page={0}", currentPageNo);