Max DateTime in a list

19,780

Solution 1

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;

Solution 2

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();

Solution 3

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;
Share:
19,780
Greens
Author by

Greens

Updated on June 04, 2022

Comments

  • Greens
    Greens almost 2 years

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

  • Beth Lang
    Beth Lang over 8 years
    thanks for adding the newer info... this is what I was looking for
  • Jlalonde
    Jlalonde about 5 years
    Also behind the scenes this is still iterating.
  • Shashank Shekhar
    Shashank Shekhar about 5 years
    @Jlalonde true but this keeps your code clean and easier to maintain