Reputation: 3055
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
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);
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