How to sort NameValueCollection using a key in C#?

橙三吉。 提交于 2020-01-03 11:45:17

问题


I've written following code and it works too - but I wanted to know whether their is better way than this :

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

回答1:


Use a SortedDictionary instead.




回答2:


Perhaps you could use a different kind of list, that supports sorting directly?

List<KeyValuePair<string, string>> optionInfoList = ...;
if (sorting) {
   optionInfoList.Sort((x,y) => String.Compare(x.Key, y.Key));
}
return optionInfoList;



回答3:


If you have to use NameValueCollection and you don't have many items in the collection, then it's fine. No need to get any fancier than that if it get's the job done.

If it's a performance bottleneck, then revisit.



来源:https://stackoverflow.com/questions/608703/how-to-sort-namevaluecollection-using-a-key-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!