2010-03-26 55 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