1

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

Thijs
  • 3,015
  • 4
  • 29
  • 54
  • Why not just call [`OrderBy`](http://msdn.microsoft.com/en-us/library/bb534966.aspx) on your collection? – Roman Oct 18 '11 at 15:05
  • 2
    Can't you use SortedDictionary or SortedList instead? Than it would be pretty easy: http://stackoverflow.com/questions/289/how-do-you-sort-a-c-sharp-dictionary-by-value , http://stackoverflow.com/questions/1250281/c-sharp-how-to-sort-a-sorted-list-by-its-value-column – Pieter Oct 18 '11 at 15:06
  • @Pieter , That's the post I was looking for but didn't found! Thank you! – Thijs Oct 18 '11 at 15:07

2 Answers2

4

Using LINQ:

var sorted = nvc.OrderBy(kvp => kvp.Value);
Oded
  • 489,969
  • 99
  • 883
  • 1,009
1

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
Mike Henry
  • 2,401
  • 1
  • 25
  • 34