如何对NameValue Collection进行排序并将其存储在字符串中

时间:2015-01-28 23:29:28

标签: c# asp.net .net linq c#-4.0

这里我将两组查询字符串参数存储到两个不同的namevalue集合中。查询字符串参数顺序可能会有所不同,所以我只想对顺序进行排序,然后我需要将namevalue集合存储到字符串中。

更新代码:

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: 排序并转换为字符串后,结果应如下所示

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

2 个答案:

答案 0 :(得分:2)

这是使用Linq的解决方案。

基本上它会使用NameValueCollectionIEnumerable更改为Cast<T>个密钥,其余部分则相当自我解释。

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])));
}

您的网址结果为:

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

电子邮件出现在nparam之前,与您预期的解决方案不同(我假设这是一个错误)。

答案 1 :(得分:1)

LINQ Dictionarylist KeyValuePair一起使用

string url1 = @"http://www.somewebsitesampletest.com/dcs7o?&data=142248494&dcp=smre&nparam=4567P&email=xxx.com";
string query1 ="";
Dictionary<String, String> paramDict = new Dictionary<string, string>();

var query = from match in urlString.Split('?').Where(m => m.Contains('='))
                .SelectMany(pr => pr.Split('&'))
            where match.Contains('=')
            select new KeyValuePair<string, String>(
                match.Split('=')[0],
                match.Split('=')[1]);

query.ToList().ForEach(kvp => paramDict.Add(kvp.Key, kvp.Value));

var List<KeyValuePair<string, string>> paramList = paramDict.ToList();

paramList.Sort();

foreach (KeyValuePair<string, int> pair in list)
{
    query1+=pair.Key+"="+pair.Value+"&";
}
query1=query1.TrimEnd('&');