[英]Find the newest item in a C# generic list using Linq
我有一個通用的項目清單。 每個項目都包含一個DateTime字段。 我想以最優雅和最有效的方式使用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();
}
為了優雅,我會根據日期時間字段對集合進行排序並返回第一個項目,如:
set.OrderByDescending(x => x.DateTime)
.FirstOrDefault();
這將創建已排序集合的內存中表示,因此效率不高。 對於未排序的集合,最有效的解決方案是循環所有項目並保存最新的。 您可以通過執行聚合操作來使用linq,我發現在語法上一團糟。
或者,您可以將項目存儲在SortedSet等已排序的集合中。 對於大多數集合,這有一個更復雜的插入時間0(log2)而不是O(1),但它允許您對日期時間進行無差別排序,因此選擇O(1)中的最新項而不是O(n)。
試試看:
var newItem = myList.OrderByDescending(item => item.yourDateTimeField).First();
嘗試聚合,即:
list.Aggregate (
DateTime.MinValue,
(lastOne, current) => current.GreaterThan (lastOne) ? current : lastOne
)
即如果你的字段是DateTimeField,你應該寫類似的東西
list.Aggregate (
null,
(lastOne, current) =>
(lastOne == null) ||
current.DateTimeField.GreaterThan (lastOne.DateTimeField)
? current
: lastOne
)
試試這個
sortlist.OrderByDescending(a => a.timeStamp).First();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.