如何在C#中使用键对NameValueCollection进行排序?

5

我已经写了下面的代码,并且它也可以工作 - 但我想知道是否有更好的方法:

 NameValueCollection optionInfoList = ..... ;
 if (aSorting)
            {
                optionInfoListSorted = new nameValueCollection();        
                String[] sortedKeys = optionInfoList.AllKeys; 
                Array.Sort(sortedKeys);
                foreach (String key in sortedKeys)
                    optionInfoListSorted.Add(key, optionInfoList[key]);

                return optionInfoListSorted;
            }
4个回答

4

5
SortedList和SortedDictionary不允许重复的键,这可能会强制某些人使用NameValueCollection。 - Nate Cook
1
如果使用NameValueCollection,并按照示例中描述的方式对其进行排序,对于重复的键,顺序是不确定的,因此该列表实际上并没有被排序,对吗? - Robert C. Barth

3
也许您可以使用一种不同类型的列表,直接支持排序?
List<KeyValuePair<string, string>> optionInfoList = ...;
if (sorting) {
   optionInfoList.Sort((x,y) => String.Compare(x.Key, y.Key));
}
return optionInfoList;

我需要将这个传递给另一个类,但是在我的方法签名中使用List<KeyValuePair>会导致代码分析错误。 - Ujwala Khaire
你能具体说明一下“代码分析错误”是什么意思吗? - dance2die

1

如果你必须使用NameValueCollection,并且集合中没有太多的项,那么这是可以接受的。如果它能完成工作,就不需要更复杂的东西。

如果它成为性能瓶颈,那么请重新考虑。


0

我创建了这个代码片段,因为我需要对查询字符串的值进行排序,以便正确比较URI:(感谢Jacob

https://dotnetfiddle.net/eEhkNk

这将保留重复的键:

public static string[] QueryStringOmissions = new string[] { "b" };

public static NameValueCollection SortAndRemove(NameValueCollection collection)
{
    var orderedKeys = collection.Cast<string>().Where(k => k != null).OrderBy(k => k);
    var newCollection = HttpUtility.ParseQueryString(String.Empty);
    foreach(var key in orderedKeys)
    {
        if (!QueryStringOmissions.Contains(key))
        {
            foreach(var val in collection.GetValues(key).Select(x => x).OrderBy(x => x).ToArray())
            {
                newCollection.Add(key, val);
            }
        }
    }
    return newCollection;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接