[SOLVED] How to Sort NameValue Collection and Store it in a string

Issue

Here I am storing two set of querystring parameters into two different namevalue collection. The querystring parameter order may vary so I just want to sort the order and then I need to store namevalue collection to a string.

Updated Code :

string url1 = @"http://www.somewebsitesampletest.com/dcs7o?data=142248494&dcp=smre&nparam=4567P&email=xxx.com";

string url2 = @"http://www.somewebsitesampletest.com/dcs7o?dcp=smre&data=142248494&email=xxx.com&nparam=4567P";

var NameValueCollection1 = HttpUtility.ParseQueryString(url1);
var NameValueCollection2 = HttpUtility.ParseQueryString(url2);

ExpectedResult:
After Sorting and converting to string the result should look like the below one

string query1 = "data=142248494&dcp=smre&email=xxx.com&nparam=4567P";
string query2 = "data=142248494&dcp=smre&email=xxx.com&nparam=4567P";

Solution

Here’s a solution using Linq.

Basically it changes the NameValueCollection to an IEnumerable of the keys using Cast<T>, then the rest is fairly self explanatory.

public string GetSortedQueryString(string url)
{
    var queryString = HttpUtility.ParseQueryString(url);

    // Ignore null keys (caused by your ?& at the start of the query string
    var orderedKeys = queryString.Cast<string>().Where(k => k != null).OrderBy(k => k);

    return string.Join("&", orderedKeys.Select(k => string.Format("{0}={1}", k, queryString[k])));
}

Results for your URLs would be:

data=142248494&dcp=smre&email=xxx.com&nparam=4567P
data=142248494&dcp=smre&email=xxx.com&nparam=4567P

Email comes before nparam, unlike your expected solution (I’m assuming that was a mistake).

Answered By – Jacob

Answer Checked By – Pedro (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *