Search code examples
c#.net-2.0

Sort Dictionary<> on value, lookup index from key


I have a Dictionary<> which I want to sort based on value so I've done this by putting the dictionary into a List<> then using the .Sort method.

I've then added this back into a Dictionary<>. Is it possible to lookup the new index/order by using the Dictionary key??

Dictionary<int, MyObject> toCompare = new Dictionary<int, MyObject>();

toCompare.Add(0, new MyObject());
toCompare.Add(1, new MyObject());
toCompare.Add(2, new MyObject());

Dictionary<int, MyObject> items = new Dictionary<int, MyObject>();
List<KeyValuePair<int, MyObject>> values = new List<KeyValuePair<int, MyObject>>   (toCompare);

// Sort.
values.Sort(new MyComparer());

// Convert back into a dictionary.
foreach(KeyValuePair<int, PropertyAppraisal> item in values)
{
      // Add to collection.
  items.Add(item.Key, item.Value);
}

// THIS IS THE PART I CAN'T DO...
int sortedIndex = items.GetItemIndexByKey(0);

Solution

  • Keep your data in the Dictionary<TKey,TValue>, but use a List<TKey> to sort the keys, then iterate as such:

    IDictionary<int, MyObject> dict = new Dictionary<int, MyObject>();
    // ... Populate dict with data.
    
    IList<int> keyList = new List<int>();
    keyList.AddRange(dict.Keys);
    
    // Sort keyList based on key's value.
    // MyObject must implement IComparable<MyObject>.
    keyList.Sort(delegate(int x, int y) {
       return dict[x].CompareTo(dict[y]);
    });
    
    foreach (int key in keyList) {
       MyObject value = dict[key];
    }
    

    This way, your list is merely a sorted index and does not affect your storage algorithm.