排序字典<> on value,从key查找索引

时间:2010-03-26 15:43:45

标签: c# .net-2.0

我有一个字典<>我想根据价值进行排序所以我通过将字典放入List<>来完成这项工作。然后使用.Sort方法。

然后我将其添加回字典<&gt ;.是否可以使用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);

2 个答案:

答案 0 :(得分: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];
}

这样,您的列表只是一个排序索引,不会影响您的存储算法。

答案 1 :(得分: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

希望这有帮助