Question

How do you get the max datetime from a list of DateTime values using C# 2.0?

Was it helpful?

Solution

Here's a simple loop to do this:

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;

OTHER TIPS

What's with all the iterating....this is very trivial

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

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

Do you mean max datetime in set, collection, or List? If so:

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

If you mean you want to know the highest possible supported value for any datetime, it's just:

DateTime.MaxValue;

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top