Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find minimal and maximal date in array using LINQ?

I have an array of classes with a property Date, i.e.:

class Record
{
    public DateTime Date { get; private set; }
}

void Summarize(Record[] arr)
{
    foreach (var r in arr)
    {
        // do stuff 
    }
}

I have to find the earliest (minimum) and the latest (maximum) dates in this array.

How can I do that using LINQ?

like image 987
abatishchev Avatar asked Jan 25 '10 13:01

abatishchev


2 Answers

If you want to find the earliest or latest Date:

DateTime earliest = arr.Min(record => record.Date);
DateTime latest   = arr.Max(record => record.Date);

Enumerable.Min, Enumerable.Max


If you want to find the record with the earliest or latest Date:

Record earliest = arr.MinBy(record => record.Date);
Record latest   = arr.MaxBy(record => record.Date);

See: How to use LINQ to select object with minimum or maximum property value

like image 164
dtb Avatar answered Oct 10 '22 12:10

dtb


old school solution without LINQ:

DateTime minDate = DateTime.MaxValue;
DateTime maxDate = DateTime.MinValue;
foreach (var r in arr) 
{
    if (minDate > r.Date)
    {
        minDate = r.Date;
    }
    if (maxDate < r.Date)
    {
        maxDate = r.Date;
    }
}
like image 42
Natrium Avatar answered Oct 10 '22 14:10

Natrium