简体   繁体   English

按通用值排序字典

[英]sort Dictionary by generic value

I have tried to sort a Dictionary object by value which is generic. 我试图按值通用排序Dictionary对象。

Here is my code 这是我的代码

Dictionary<string, ReportModel> sortedDic = new Dictionary<string, ReportModel>();
Dictionary<string, ReportModel> rDic = new Dictionary<string, ReportModel>();
var ordered = sortedDic.OrderByDescending(x => x.Value.totalPurchase);
foreach (var item in ordered)
{                           
    rDic.Add(item.Key, item.Value);
}

The variable, ordered, just has the same order like sortedDic. 有序的变量与sortedDic具有相同的顺序。 What is wrong with this? 这有什么问题? Any idea? 任何想法?

This happens because Dictionary is generally an unordered container * . 这是因为Dictionary通常是无序容器* When you put the data into rDic , it becomes unordered again. 当您将数据放入rDic ,它将再次变为无序。

To retain the desired order, you need to put the results into a container that explicitly keeps the ordering that you supply. 要保留所需的顺序,您需要将结果放入一个明确保持您提供的顺序的容器中。 For example, you could use a list of KeyValuePair<string,ReportModel> , like this: 例如,您可以使用KeyValuePair<string,ReportModel> ,如下所示:

IList<KeyValuePair<string,ReportModel>> ordered = sortedDic
    .OrderByDescending(x => x.Value.totalPurchase)
    .ToList();


* Due to the way the Dictionary<K,V> is implemented by Microsoft, it happens to retain the insertion order , but that is incidental and undocumented, so it may change in the future versions, and should not be relied upon. *由于Microsoft Dictionary<K,V>的实现方式, 它恰好保留了插入顺序 ,但这是偶然的和未记录的,所以它可能在将来的版本中发生变化,不应该依赖。

When adding the items back to the dictionary, it would not keep their order. 将项目添加回字典时,它不会保留其顺序。 You can either: 你可以:

  1. Use the following implementation . 使用以下实现
  2. Use a list in the below form. 使用下面表格中的列表。

     IEnumrable> lst= IEnumrable> lst =\n   sortedDic.OrderByDescending(x => x.Value.totalPurchase).ToArray(); sortedDic.OrderByDescending(x => x.Value.totalPurchase).ToArray(); 
  3. [EDIT] If you don't mind the key changing then you can use SortedDictionary<,>. [编辑]如果您不介意更改密钥,则可以使用SortedDictionary <,>。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM