且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

LINQ:如何集合中的所有对象的属性执行。最大()中,用最大值返回对象

更新时间:2023-01-21 07:41:06

我们有一个扩展方法做的正是这 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);

这是比任何这里psented以外迈赫达德的第二个解决方案解决方案$ P $的更好(IMO)(这基本上是一样的 MaxBy ):

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),不像上发现每次迭代的最大值 previous接受的答案(使它为O(n ^ 2))

  • 排序的解决方案是O(n log n)的

  • 服用最高值,然后找到与该值的第一个元素是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