Pergunta

Como você recebe o datetime máximo de uma lista de valores DateTime usando C # 2.0?

Foi útil?

Solução

Aqui está um loop simples de fazer isso:

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;

Outras dicas

O que é com toda a iteração .... isso é muito trivial

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

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

Você quer dizer datetime max em conjunto, coleção, ou List ? Se assim for:

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

Se você quer dizer que você quer saber o valor mais alto suportado possível para qualquer data e hora, é só:

DateTime.MaxValue;

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

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top