Sort Dictionary<> on value, lookup index from key
Posted
by paulio
on Stack Overflow
See other posts from Stack Overflow
or by paulio
Published on 2010-03-26T15:43:45Z
Indexed on
2010/03/26
15:53 UTC
Read the original article
Hit count: 151
c#
Hi,
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);
© Stack Overflow or respective owner