列表中的最大日期时间

Posted

技术标签:

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

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

【问题讨论】:

需要...更多...信息...在循环中获取最大日期时间,wtf 吗?什么的最大日期时间?那个循环是做什么的? 【参考方案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();

【讨论】:

以上是关于列表中的最大日期时间的主要内容,如果未能解决你的问题,请参考以下文章