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?
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
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;
    }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With