c# - 按值对字典进行排序,该值是具有 DateTime 的对象

标签 c# .net datetime dictionary

我有一个结构测试,我将其作为值添加到字典中。 我想要做的是按值的日期时间对字典进行排序。

    struct Test
    {
        DateTime dt;
        public string ID;
    }

    Dictionary<String, Test> dict = new Dictionary<String,Test>();
    Test t = new Test();

    t.dt = DateTime.Now;
    t.ID = "XUDF";
    dict.Add(t.ID, t);

    t.dt = DateTime.Now.AddDays(17);
    t.ID = "RFGT";
    dict.Add(t.ID, t);

    t.dt = DateTime.Now.AddDays(3);
    t.ID = "ADLV";
    dict.Add(t.ID, t);

    t.dt = DateTime.Now.AddHours(2);
    t.ID = "SKFU";
    dict.Add(t.ID, t);

我不确定这之后要做什么。 另外,这是最好的方法吗? 我正在使用 .net 3

我想要做的是有一个列表,我可以通过 ID 访问它,但也可以按 t.dt 中的日期时间排序。 我希望能够通过 ID 选择一个对象,但也能够遍历并让它按日期时间顺序出现。

最佳答案

“字典排序”是什么意思?字典本身没有“顺序”。它是一个键控集合,其底层实现是一个哈希表。

我假设您的意思是,“我想按值的顺序枚举字典的内容。”可以这样做:

public void List( Dictionary<string,DateTime> dict )
{
  int i = 0 ;
  foreach( KeyValuePair<string,DateTime> entry in dict.OrderBy( x => x.Value ).ThenByDescending( x => x.Key ) )
  {
    Console.WriteLine( "{0}. Key={1}, Value={2}" , ++i , entry.Key , entry.Value ) ;
  }
  Console.WriteLine( "The dictionary contained a total of {0} entries." , i ) ;
}

如果另一方面,您确实想要/需要一个有序的集合,则需要说明您的实际需求是什么。

关于c# - 按值对字典进行排序,该值是具有 DateTime 的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7198724/

相关文章:

c# - 指数数组的边界之外

c# - 为层次结构中的实体获取父级

c# - .NET Framework 4.7 Web 应用程序中的 AntiXSS - 如何应用它

c# - 为什么释放鼠标按钮时绘制的线会消失?

python - 如何调整时区的 `strftime`?

c# - 控制台应用程序不会定期刷新输出

c# - 我可以从 BindingSource 获取项目类型吗?

c# - 没有什么等于 String.Empty,null 不等于 String.Empty,我在这里缺少什么?

MySQL DATETIME 使用虚拟日期表排序

php - DateTime 7 天后的 00 :00