使用 Linq 在 C# 泛型列表中查找最新项

本文关键字:查找 最新 列表 泛型 Linq 使用 | 更新日期: 2023-09-27 18:35:46

>我有一个通用的项目列表。每个项目都包含一个日期时间字段。我想使用 Linq 以最优雅、最有效的方式查找列表中的最新项目。

就我而言,优雅比效率更重要,但以有效的方式做到这一点会很好。

谢谢。

看完答案后:这是代码(也是我喜欢的答案):

using System.Collections.Generic;
using System.Linq;
class Item
{
    public Item Date { get; set; }
    public string Name { get; set; }
}
static void Main(string[] args)
{
    List<Item> items = CreateItems();
    Item newest;
    if (items.Count == 0)
        newest = null;
    else
        newest = items.OrderByDescending(item => item.Date).First();
}

使用 Linq 在 C# 泛型列表中查找最新项

为了优雅起见,我会根据日期时间字段对集合进行排序并返回第一项,如下所示:

set.OrderByDescending(x => x.DateTime)
   .FirstOrDefault();

这将创建已排序集合的内存中表示形式,因此效率不是那么好。对于未排序的集合,最有效的解决方案是遍历所有项目并保存最新的项目。您可以通过执行聚合操作来使用 linq,我觉得语法上一团糟。

或者,您可以将项目存储在排序集合(如 SortedSet)中。对于大多数集合,这具有更复杂的插入时间 0(log2) 而不是 O(1),但它允许您立即按日期时间排序,因此在 O(1) 而不是 O(n) 中选择最新项目。

到目前为止,大多数解决方案都必须首先对列表进行完全排序(通过 OrderByDescending),这是不必要且耗时的。你想要的是Jon Skeet的MoreLinq MaxBy函数。MaxBy 的来源在谷歌代码上。

var newest = thelist.MaxBy(x => x.DateTimeField);

试试:

var newItem = myList.OrderByDescending(item => item.yourDateTimeField).First();

尝试聚合,即:

list.Aggregate (
    DateTime.MinValue,
    (lastOne, current) => current.GreaterThan (lastOne) ? current : lastOne
)

即,如果你的字段是日期时间字段,你应该写类似的东西

list.Aggregate (
    null,
    (lastOne, current) => 
        (lastOne == null) ||
             current.DateTimeField.GreaterThan (lastOne.DateTimeField)
        ? current
        : lastOne
)

试试这个

 sortlist.OrderByDescending(a => a.timeStamp).First();