我有类数组的形式与属性日期
,即:
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.
我如何能做到这一点使用LINQ?
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);
请参阅:How使用LINQ选择以最小的或最大的属性值对象