-1

We want to remove query string (a,b,c,d) and add query string (z). For example:

Input: /example.com/?a=1&b=2&c=3&d=4&e=5&f=6
Output: /example.com/?&e=5&f=6&z=6

Dictionary<string, string> dict = new Dictionary<string, string>();
    foreach (var key in Request.QueryString.AllKeys)
    {
        if (key != "a" && key != "b" && key != "c" && key != "d")
        {
            dict.Add(key, Request.QueryString[key]);
        }
    }
queryString = string.Join("&", dict.Select(x => x.Key + "=" + x.Value));

if (!string.IsNullOrEmpty(queryString ))
{
    searchViewModel.CurrQS += "&z=6";
}

I have done this so far. But is it worth converting this to dictionary and then to string for this. Any other better method?

Manfred Radlwimmer
  • 13,257
  • 13
  • 53
  • 62
Sahil Sharma
  • 3,847
  • 6
  • 48
  • 98

1 Answers1

0
Dictionary<string, string> dict = new Dictionary<string, string>();
    foreach (var key in Request.QueryString.AllKeys)
    {
        if (key != "a" && key != "b" && key != "c" && key != "d")
        {
            dict.Add(key, Request.QueryString[key]);
        }
    }

queryString = Request.RawUrl.Split(new[] {'?'})[0] +
              string.Join("&", dict.Select(x => x.Key + "=" + x.Value));

if (!string.IsNullOrEmpty(queryString ))
{
    queryString  += "&z=6";
}

Easy way out of this is, if you have url then do this:

var stringURL = Request.RawUrl.Split(new[] {'?'});
var urlwithoutQuerystring=stringURL.First();
var newUrl = urlwithoutQuerystring + "?c=abc"

or do like this

var stringURL = Request.RawUrl.Split(new[] {'?'})[0];
var newUrl = strinULR + "?c=abc"
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263