按键和值对字典排序?

时间:2011-03-03 12:12:18

标签: c# .net sorting dictionary

如果我想在C#中对字典进行排序,其顺序由其键及其值确定。类似于其值的降序和具有相同值的降序,按其键降序。似乎很有可能只按键或仅按值排序,但两者都非常烦人。

2 个答案:

答案 0 :(得分:25)

using System.Linq;
...
IOrderedEnumerable<KeyValuePair<TKey, TValue>> sortedCollection = myDictionary
                    .OrderByDescending(x => x.Value)
                    .ThenByDescending(x => x.Key);

答案 1 :(得分:1)

如果您需要更复杂的订购方案,请实施IComparer&gt;在OrderBy或OrderByDescending的重载版本中使用。