c# - 根据值而不是键对 SortedDictionary 进行排序

标签 c#

我有一个 SortedDictionary,键是一个 int 值,每个键的匹配值是一个类对象。该类包含一个 int 和两个日期时间变量。

我需要根据类(class)中的 InTime 日期时间对 SortedDictionary 进行排序。因此,当我执行 foreach 循环遍历我的 SortedDictionary 时,我将根据日期时间对它们进行排序。

这可能吗?我怎样才能实现它?

enter code here
 class Busdetail
    {
        public int BusNo { get; set; }
        public DateTime InTime { get; set; }
        public DateTime OutTime { get; set; }
    }

最佳答案

Sorted Dictionary 将始终按键排序,因此无法重新排列它的数据,因此它们会按键以外的任何内容排序。您可以做的是将数据放入另一个结构(某种 IOrderedEnumerable ),在其中可以根据键以外的其他内容对数据进行排序。

如果你想丢弃键而只获取值,那么

var sortedValues = dictionary.Values.OrderBy(busDetail => busDetail.InTime);

将起作用,并且 sortedValues 的类型将为 IOrderedEnumerable<BusDetail> . 如果您仍然需要保留键和值,您可以这样做:

var sortedElements = dictionary.OrderBy(kvp => kvp.Value.InTime);

这将返回 IOrderedEnumerable<KeyValuePair<int, BusDetail>> . 你可以foreach在这两个集合中的任何一个上,或者您可以将它们绑定(bind)到网格的数据源。

关于c# - 根据值而不是键对 SortedDictionary 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3417296/

相关文章:

c# - 在 mongodb 和 Entityframework 中使用相同的 C# Poco 类

c# - 使用 Task.Factory.StartNew().ContinueWith() 的单元测试代码

c# - ViewModel 中对象的验证不添加 CSS 验证类

c# - 将路径转换为几何形状

c# - 如何使用 linq 使用文件名从目录中过滤文件?

c# - Enumerable.Max() 如果有两个最大值

c# - 如何将 IList 复制到相同类型的 IList?

c# - 如何从其 Win32 句柄中获取 System.Windows.Form 实例?

c# - JIT简单优化

c# - 使用 WebRequest 注册自定义协议(protocol)