开发者

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 (maxim开发者_运维技巧um) 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;
    }
}


The two in one LINQ query (and one traversal):

arr.Aggregate(
    new { MinDate = DateTime.MaxValue,
          MaxDate = DateTime.MinValue },
    (accDates, record) => 
        new { MinDate = record.Date < accDates.MinDate 
                        ?  record.Date 
                        : accDates.MinDate,
              MaxDate = accDates.MaxDate < record.Date 
                        ?  record.Date 
                        : accDates.MaxDate });


Using lambda expressions:

void Summarise(Record[] arr)
{
    if (!(arr == null || arr.Length == 0))
    {
        List<Record> recordList = new List<Record>(arr);
        recordList.Sort((x,y) => { return x.Date.CompareTo(y.Date); });

        // I may have this the wrong way round, but you get the idea.
        DateTime earliest = recordList[0];
        DateTime latest = recordList[recordList.Count];
    }
}

Essentially:

  • Sort into a new list in order of date
  • Select the first and last elements of that list

UPDATE: Thinking about it, I'm not sure that this is the way to do it if you care at all about performance, as sorting the entire list will result in many more comparisons than just scanning for the highest / lowest values.


I'd just make two properties Min,Max, assign them the value of the first item you add to the array, then each time you add a new item just check if its DateTime is less or greater than the Min Max ones.

Its nice and fast and it will be much faster than iterating through the array each time you need to get Min Max.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜