从列表中获取< t>具有特定属性最大值的记录 [英] Get from a List<t> the record with the maximum value of a specific property
问题描述
Possible Duplicate:
LINQ: How to perform .Max() on a property of all objects in a collection and return the object with maximum value
我有以下课程:
class Product
{
public string ProductName { get; set; }
public DateTime ActivationDate { get; set; }
}
然后我创建并填充一个List<Product>
,我想从Product
中获取最新的ActivationDate
中的ProductName
.
Then I create and fill a List<Product>
and I would like to get the ProductName
from the Product
with the latest ActivationDate
.
Product.Where(m => m.ActivationDate == Max(m.ActivationDate)).Select(n => n.ProductName)
Product.Max(m => m.ActivationDate).Select(n => n.ProductName)
但是机器人方法不起作用.有人知道实现此任务的方法吗?
but bot methods do not work. Does anybody know a way to achieve this task?
推荐答案
您可以在ActivationDate字段上OrderByDescending
List<Product>
,然后使用FirstOrDefault()
You can OrderByDescending
the List<Product>
on the ActivationDate Field and then take FirstOrDefault()
Product.OrderByDescending(p => p.ActivationDate).FirstOrDefault();
对于更简单的版本,有一个扩展方法
For a more simpler version there is an extension method
Product.MaxBy(p => p.ActivationDate);
这篇关于从列表中获取< t>具有特定属性最大值的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!