Pregunta

¿Cómo se obtiene la fecha y hora máxima de una lista de valores de DateTime usando C # 2.0?

¿Fue útil?

Solución

Aquí hay un bucle simple para hacer esto:

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;

Otros consejos

¿Qué pasa con toda la iteración ... esto es muy trivial

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

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

¿Se refiere a la fecha y hora máxima en conjunto, colección o Lista ? Si es así:

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

Si quiere decir que desea conocer el valor admitido más alto posible para cualquier fecha y hora, es solo:

DateTime.MaxValue;

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top