【问题标题】:Max DateTime in a list列表中的最大日期时间
【发布时间】:2009-09-17 16:37:58
【问题描述】:

如何使用 C# 2.0 从 DateTime 值列表中获取最大日期时间?

【问题讨论】:

  • 需要...更多...信息...在循环中获取最大日期时间,wtf 吗?什么的最大日期时间?那个循环是做什么的?

标签: c# c#-2.0


【解决方案1】:

所有的迭代是怎么回事....这是非常微不足道的

// Given...
List<DateTime> dates = { a list of some dates... }

// This is the max...
DateTime MaxDate = dates.Max();

【讨论】:

  • 感谢您添加更新的信息...这就是我想要的
  • 这也在幕后迭代。
  • @Jlalonde 是的,但这可以使您的代码保持干净且易于维护
【解决方案2】:

这是一个简单的循环:

List<DateTime> dates = new List<DateTime> { DateTime.Now, DateTime.MinValue, DateTime.MaxValue };

DateTime max = DateTime.MinValue; // Start with the lowest value possible...
foreach(DateTime date in dates)
{
    if (DateTime.Compare(date, max) == 1)
        max = date;
}

// max is maximum time in list, or DateTime.MinValue if dates.Count == 0;

【讨论】:

    【解决方案3】:

    您是指集合、集合还是列表中的最大日期时间?如果是这样:

    DateTime max = DateTime.MinValue;
    foreach (DateTime item in DateTimeList)
    {
        if (item > max) max = item;
    }
    return max;
    

    如果您的意思是您想知道任何日期时间可能支持的最高值,那就是:

    DateTime.MaxValue;
    

    【讨论】:

      【解决方案4】:

      var max = new[] { datetime1, datetime2 }.Max();

      【讨论】:

        猜你喜欢
        • 2015-12-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-10
        • 1970-01-01
        相关资源
        最近更新 更多