问题描述
我有一个具有两个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()并返回具有最大值的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!