views:

94

answers:

3

I have a requirement to retrieve an item from a data structure by key. But I also have a requirement to traverse that data structure in sorted order, using a field other than the key.

Something like this (pseudocode, for illustrative purposes only):

var list = new SortedDictionary<TKey, TSortField, TItem>();

How would I do this? Is there a way to use a single data structure, or do I need to roll my own?

NOTE: TItem already derives from (and implements)IComparable<T>.

+2  A: 

If you're not going to be modifying the result of the sort, you could use a combination of IEnumerable.OrderBy and ToDictionary:

var sortedResult = sortedDictionary.OrderBy(kvp => kvp.Value.SortField)
                                   .ToDictionary(kvp => kvp.Key,
                                                 kvp => kvp.Value);

Just keep in mind that this is really creating a new collection rather than sorting the original (which will be maintained in the SortedDictionary).

Justin Niessner
+1  A: 

The SortedDictionary class has a Values property that "Gets a collection containing the values in the SortedDictionary". That collection is an IEnumerable and you can sort that collection of values.

Here is an example program in C# (I wrote it quickly as an example. It probably could be improved and/or changed based on your specific needs).

using System;
using System.Collections.Generic;
using System.Linq;


namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            SortedDictionary<string, int> sd = new SortedDictionary<string, int>();

            sd.Add("a", 10);
            sd.Add("c", 4);
            sd.Add("b", 20);

            Console.WriteLine("___KEYS____");
            foreach (string key in sd.Keys)
            {
                Console.WriteLine(key);
            }

            foreach(int sortedVal in sd.Values.OrderBy(value => value))
            {
                Console.WriteLine(sortedVal);
            }
        }
    }
}
Adam Porad
A: 

Adding the items to a SortedList will only store references to the objects already in memory so it won't take up much more room.

Jason Goemaat