Ujwala Khaire
Ujwala Khaire

Reputation: 574

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

Upvotes: 5

Views: 6351

Answers (4)

jaybro
jaybro

Reputation: 1563

I made this fiddle because I needed to sort querystring values in order to properly compare URIs: (H/T to Jacob)

https://dotnetfiddle.net/eEhkNk

This preserves duplicate keys:

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

Upvotes: 0

Ryan Emerle
Ryan Emerle

Reputation: 15811

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.

Upvotes: 1

Robert C. Barth
Robert C. Barth

Reputation: 23325

Use a SortedDictionary instead.

Upvotes: 4

Guffa
Guffa

Reputation: 700432

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;

Upvotes: 3

Related Questions