如何对集合中所有对象的属性执行 .Max() 并返回具有最大值的对象 [英] How to perform .Max() on a property of all objects in a collection and return the object with maximum value

查看:34
本文介绍了如何对集合中所有对象的属性执行 .Max() 并返回具有最大值的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有两个 int 属性的对象列表.该列表是另一个 linq 查询的输出.对象:

I have a list of objects that have two int properties. The list is the output of another linq query. The object:

public class DimensionPair  
{
    public int Height { get; set; }
    public int Width { get; set; }
}

我想在列表中查找并返回具有最大Height 属性值的对象.

I want to find and return the object in the list which has the largest Height property value.

我可以设法获得 Height 值的最高值,但不能获得对象本身.

I can manage to get the highest value of the Height value but not the object itself.

我可以用 Linq 做这件事吗?怎么样?

Can I do this with Linq? How?

推荐答案

我们有一个 扩展方法MoreLINQ 中做到这一点.您可以查看那里的实现,但基本上这是一个遍历数据的情况,记住我们迄今为止看到的最大元素以及它在投影下产生的最大值.

We have an extension method to do exactly this in MoreLINQ. You can look at the implementation there, but basically it's a case of iterating through the data, remembering the maximum element we've seen so far and the maximum value it produced under the projection.

在您的情况下,您会执行以下操作:

In your case you'd do something like:

var item = items.MaxBy(x => x.Height);

除了 Mehrdad 的第二个解决方案(与 MaxBy 基本相同)之外,这比此处介绍的任何解决方案都更好 (IMO):

This is better (IMO) than any of the solutions presented here other than Mehrdad's second solution (which is basically the same as MaxBy):

  • 之前接受的答案不同,它是 O(n),它在每次迭代中找到最大值(使其成为 O(n^2))
  • 排序解决方案是 O(n log n)
  • Max 值,然后找到具有该值的第一个元素是 O(n),但遍历序列两次.在可能的情况下,您应该以单程方式使用 LINQ.
  • 阅读和理解比聚合版本简单得多,并且每个元素只计算一次投影
  • It's O(n) unlike the previous accepted answer which finds the maximum value on every iteration (making it O(n^2))
  • The ordering solution is O(n log n)
  • Taking the Max value and then finding the first element with that value is O(n), but iterates over the sequence twice. Where possible, you should use LINQ in a single-pass fashion.
  • It's a lot simpler to read and understand than the aggregate version, and only evaluates the projection once per element

这篇关于如何对集合中所有对象的属性执行 .Max() 并返回具有最大值的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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