从列表中获取< t>具有特定属性最大值的记录 [英] Get from a List<t> the record with the maximum value of a specific property

查看:71
本文介绍了从列表中获取< t>具有特定属性最大值的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
LINQ:如何对集合中所有对象的属性执行.Max()并返回具有最大值的对象

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

MaxBy

Product.MaxBy(p => p.ActivationDate);

这篇关于从列表中获取&lt; t&gt;具有特定属性最大值的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆