繁体   English   中英

c# 中的 orderedDictionary 的 OrderByDescending

[英]OrderByDescending for orderedDictionary in c#

我已经宣布了一个有序的字典。 我试图根据它的值按降序对它进行排序,但发现“ordereddictionary 不包含 OrderByDescending 的定义”。

 dic = dic.OrderByDescending(d => d.Value.Count).ToDictionary(x => x.Key, x => x.Value); 

// 字典声明

OrderedDictionary dic = new OrderedDictionary(StringComparer.CurrentCultureIgnoreCase); 

该字典的键字段包含字符串,值包含字符串列表。 我正在尝试根据每个键包含的值的数量降序重新排列它。 有关如何执行此操作的任何建议。

OrderedDictionary是一个非泛型集合,而 LINQ 方法(例如OrderByDescending )几乎只对泛型类型IEnumerable<T>进行操作。

请注意,即使您的调用已编译,它也不一定会执行您想要的操作 - 因为您随后调用ToDictionaryDictionary<,>结果结束......并且Dictionary<,>保证保留任何类型秩序。

如果您实际上不需要对结果执行查找,则可以在排序后创建一个键/值对列表。 我们目前不知道您是否需要OrderedDictionary开始,但您可以考虑使用通用的SortedDictionary<,>类型,这样您就可以在其上使用 LINQ。 所以你会有类似的东西:

var source = new SortedDictionary<string, List<string>>(StringComparer.CurrentCultureIgnoreCase);
// Populate the dictionary here

// This is a List<KeyValuePair<string, List<string>>>
var orderedByCount = source
    .OrderByDescending(pair => pair.Value.Count)
    .ToList();

暂无
暂无

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

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