Is there any easy way to sort NameValueCollection on the basis of key in C#?
Asked Answered
M

2

6

I am looking for an easy way to sort NameValueCollection on the basis of key - it should not be a performance heavy though.

Meteor answered 9/3, 2009 at 19:59 Comment(0)
H
13

Start with SortedDictionary<string,string> or SortedList<string,string> and you're already there...

If you need the multiple items per key, then consider a SortedDictionary<string,List<string>>. There are ways to simplify addition etc with extension methods - it needn't be scary.

Note also that NameValueCollection is case-insensitive, so you might need to use one of the insensitive comparisons - for example:

Dictionary<string,string> data = new Dictionary<string,string>(
            StringComparer.InvariantCultureIgnoreCase);

(edit) here's an example of using an extension method to populate multiple values against a single key in C# 3.0:

    static void Main()
    {
        var data = new Dictionary<string, List<string>>(
            StringComparer.InvariantCultureIgnoreCase);
        data.Add("abc", "def");
        data.Add("abc", "ghi");
    }

    static void Add<TKey, TValue>(this IDictionary<TKey, List<TValue>> lookup,
        TKey key, TValue value)
    {
        List<TValue> list;
        if (!lookup.TryGetValue(key, out list))
        {
            list = new List<TValue>();
            lookup.Add(key, list);
        }
        list.Add(value);
    }
Honk answered 9/3, 2009 at 20:7 Comment(0)
N
2

Here's a brute force hack that I'm not too proud of, but it works if you need something quick and dirty.

public static void Sort(this NameValueCollection nameValueCollection)
    {
        // Create a temporary collection the same size as the original
        NameValueCollection tempNameValueCollection = new NameValueCollection(nameValueCollection.Count);

        // Sort the keys
        string[] keys = nameValueCollection.AllKeys;
        Array.Sort(keys);

        foreach (string key in keys)
        {
            // Sort the values
            string[] values = nameValueCollection[key].Split(',');
            Array.Sort(values);

            // Add each value to the temporary collection
            foreach (string value in values)
            {
                tempNameValueCollection.Add(key, value);
            }
        }

        // Clear the original collection
        nameValueCollection.Clear();

        // Add the sorted entries back
        nameValueCollection.Add(tempNameValueCollection);
    }
Nola answered 9/3, 2009 at 20:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.