c# - 使用 LINQ 在数组中查找最小和最大日期?

标签 c# .net linq arrays search

我有一组具有属性 Date 的类,即:

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

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

我必须在此数组中找到earliest(最小)和latest(最大)日期。

我如何使用 LINQ 做到这一点?

最佳答案

如果要查找最早或最晚的日期:

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

Enumerable.Min , Enumerable.Max


如果要查找日期最早或最晚的记录:

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

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

关于c# - 使用 LINQ 在数组中查找最小和最大日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2132615/

相关文章:

c# - 为什么 POCO 对象是使用类而不是结构创建的

c# - SSH.NET "Server string is null or empty"异常

.net - VS2010用UnitTestFramework升级

c# - 数值不适合 System.Decimal

c# - 检索 XML 文件中的深层嵌套值

c# - 在另一个 List<string> 中匹配 List<string> 中的部分字符串

c# - 简单乘法

c# - 如何在 .NET 4.6 上使用 .NET Core 的 IdentityServer4?

.net - Visual Studio Shell - 创建自定义 IDE

c# - 动态更改月份列表