Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort NameValueCollection using a key in C#?

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;
            }
like image 720
Ujwala Khaire Avatar asked Mar 03 '09 23:03

Ujwala Khaire


2 Answers

Use a SortedDictionary instead.

like image 195
Robert C. Barth Avatar answered Oct 14 '22 12:10

Robert C. Barth


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;
like image 30
Guffa Avatar answered Oct 14 '22 12:10

Guffa