Monday, April 11, 2011

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;
            }
From stackoverflow
  • 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;
    
    : I need to pass this to another class and having List in my method signatures gives me Code Analysis errors.
    Sung Meister : Would you be specific by what you mean by "Code Analysis Errors"?
  • Use a SortedDictionary instead.

    Marc Gravell : +1; or SortedList<,>, depending on the scenario.
  • 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.

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.