2010-03-26 57 views
1

我有一个字典<>我想根据价值排序,所以我已经通过将字典放入列表<>然后使用.Sort方法。排序字典<>值,从关键字查找索引

我已经添加回到词典<>。是否可以通过使用Dictionary键来查找新的索引/顺序?

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); 
+1

不是词典的顺序在C#defenition未定义? – Wouter 2010-03-26 15:46:12

+1

你想要做什么?如果您需要独特的集合,请使用字典。如果您需要排序列表中项目的索引,请使用SortedList。 – 2010-03-26 15:46:41

+0

@Michael Todd:'SortedList'不是正确的解决方案。他希望根据集合中*值*的自定义比较来订购商品。 – 2010-03-26 15:57:49

回答

3

让您的数据在Dictionary<TKey,TValue>,但使用List<TKey>的键进行排序,然后遍历这样:

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]; 
} 

这样,你的清单仅仅是一个排序的指标,并不会影响您的存储算法。

+0

你有更多的参与的例子,因为我需要按价值而不是按键排序。另外,我在.net 2.0上。 – paulio 2010-03-26 16:45:20

+1

新增了对代码段的排序。 – spoulson 2010-03-26 18:37:44

+0

感谢您的回答。 – paulio 2010-03-28 22:24:29

0

借此扩展方法:

public static Dictionary<TKey, TValue> Sort<TKey, TValue, TSortingKey>(this Dictionary<TKey, TValue> source, 
    Func<KeyValuePair<TKey, TValue>, TSortingKey> selector) 
{ 
    var result = new Dictionary<TKey, TValue>(); 
    foreach (var pair in source.OrderBy(selector)) 
     result.Add(pair.Key, pair.Value); 
    return result; 
} 

与用法:

Dictionary<int, MyType> source = new Dictionary<int, MyType>(); 
    Dictionary<int, MyType> sortedDictionary = source.Sort(i => i.Value.Property1); //sort dictionary by values (by property "Property1" of type MyType 

希望这有助于

+0

不幸的是我被困在.net 2.0中 – paulio 2010-03-26 16:04:19