Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Can this code be improved? I'm avoiding using the QueryString collection because the query string may contain eg: OrderBy=Column1&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 > 0)
        {
            var kvp =
                query.Split('&').Select(x => x.Split('='))
                    .Select(x => new { Key = x[0], Value = (x.Length > 0) ? x[1] : ""})
                    .Where(x => x.Key != "page")
                    .ToList();
            kvp.Add(new { Key = "page", Value = number.ToString() });
            query = String.Join("&", kvp.Select(x => x.Key + "=" + x.Value).ToArray());
        }
        else query = String.Format("page={0}", number);
    }
share|improve this question
Why do you think it won't be helpful to switch to QueryString["OrderBy"]=="Column1,Column2". It seems to be more regular structure than several parameters with the same name. – Snowbear Jun 1 '11 at 16:39
The original query string comes from form data. MVC binds the multiple "OrderBy" as an IEnumerable<string>. If I convert the QueryString collection into a RouteValuesDictionary to recycle the query string the IEnumerable only has one value, and it breaks the view as a result. I guess it would be a valid suggestion to have the controller handle both cases gracefully. – mootinator Jun 1 '11 at 17:18

1 Answer

up vote 1 down vote accepted

I think that yes this code can be improved.

use a regular expression:

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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.