tags:

views:

424

answers:

3

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

A: 

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;
Reed Copsey
+2  A: 

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;
Joel Coehoorn
+1  A: 

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();
This is good, but you need .NET 3.5.
Joe Daley