从列表中获取具有最大日期的记录
Get a record from List with the max date
我在 List of actionHistorys 中有几条记录,我试图从中获取一条 MyactionHistory 类型的记录,该记录具有最大 createdate 字段。 CreateDateTime 是一个日期时间字段。
我尝试查找和搜索但找不到解决方案
List<MyActionHistory> actionHistorys = oFD.GetMyActionHistoryList(); // This should have about 4 objects or records
// This is where I am confused..Not working
MyActionHistory MaxRecord= actionHistorys.Find(p => actionHistorys.Exists(o => o.CreateDateTime ))
我建议使用 MoreLINQ MaxBy
使用
using System.Linq;
using System.Collections.Generic;
using MoreLinq;
代码
MyActionHistory maxRecord = actionHistorys
.MaxBy(o => o.CreateDateTime)
.Take(1)
.FirstOrDefault();
这比对整个列表进行降序排序然后取第一项更有效。如果我正确理解 MaxBy 和 Take 的实现,这将使单次通过列表并 return 具有最高值的(如果多个具有相同的最高值,则第一个具有最高值)。
感谢@timur。以下代码有效
actionHistorys.OrderByDescending(h => h.CreateDateTime).First();
试试这个:
MyActionHistory MaxRecord = actionHistorys.OrderBy((x) => x.CreateDateTime).LastOrDefault();
或者:
MyActionHistory MaxRecord = actionHistorys.OrderByDescending((x) => x.CreateDateTime).FirstOrDefault();
我在 List of actionHistorys 中有几条记录,我试图从中获取一条 MyactionHistory 类型的记录,该记录具有最大 createdate 字段。 CreateDateTime 是一个日期时间字段。
我尝试查找和搜索但找不到解决方案
List<MyActionHistory> actionHistorys = oFD.GetMyActionHistoryList(); // This should have about 4 objects or records
// This is where I am confused..Not working
MyActionHistory MaxRecord= actionHistorys.Find(p => actionHistorys.Exists(o => o.CreateDateTime ))
我建议使用 MoreLINQ MaxBy
使用
using System.Linq;
using System.Collections.Generic;
using MoreLinq;
代码
MyActionHistory maxRecord = actionHistorys
.MaxBy(o => o.CreateDateTime)
.Take(1)
.FirstOrDefault();
这比对整个列表进行降序排序然后取第一项更有效。如果我正确理解 MaxBy 和 Take 的实现,这将使单次通过列表并 return 具有最高值的(如果多个具有相同的最高值,则第一个具有最高值)。
感谢@timur。以下代码有效
actionHistorys.OrderByDescending(h => h.CreateDateTime).First();
试试这个:
MyActionHistory MaxRecord = actionHistorys.OrderBy((x) => x.CreateDateTime).LastOrDefault();
或者:
MyActionHistory MaxRecord = actionHistorys.OrderByDescending((x) => x.CreateDateTime).FirstOrDefault();