Thijs
Thijs

Reputation: 3055

Sorting a NameValueCollection by value in c#

I have a NameValueCollection and I would like to sort this on his value. Does anyone got some ideas how to do this easely? I was thinking to wrap it into a SortedList or SortedDictionairy but I'm not sure how to get started.

Thijs

Upvotes: 1

Views: 1865

Answers (2)

Mike Henry
Mike Henry

Reputation: 2441

I think the complexity of the solution depends on whether you care about multiple values per key. If you only need to sort the first value per key, the following should return the sorted result as an IEnumerable<KeyValuePair<string, string>>:

var sorted = nvc.AllKeys.OrderBy(key => nvc[key])
                .Select(key => new KeyValuePair<string, string>(key, nvc[key]));

If you care about multiple values per key, you may have to split each value into a KeyValuePair before sorting them. Something like:

var sorted = nvc.AllKeys
                .SelectMany(key =>
                    nvc.GetValues(key)
                       .Select(val => new KeyValuePair<string, string>(key, val)))
                .OrderBy(kvp => kvp.Value);

Examples:

Given:

var nvc = new NameValueCollection() {
    { "key1", "c" },
    { "key1", "a" },
    { "key2", "b" }
};

The first example should return the following IEnumerable<KeyValuePair<string, string>>:

key2: b
key1: c,a

The second example should return the following IEnumerable<KeyValuePair<string, string>>:

key1: a
key2: b
key1: c

Upvotes: 1

Oded
Oded

Reputation: 499092

Using LINQ:

var sorted = nvc.OrderBy(kvp => kvp.Value);

Upvotes: 4

Related Questions