更新时间: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),但遍历序列的两倍。如果可能的话,你应该在单通方式使用LINQ。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.