C# 是否有等效的 std::nth_element ?
我正在将一些 C++ 代码移植到 C#。
C# 是否有相当于 std::nth_element()
还是我需要自己动手?
I'm porting some C++ code to C#.
Does C# have an equivalent to std::nth_element()
or do I need to roll my own?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

我假设您正在寻找一个访问器,通过对集合执行部分排序来返回无序集合的第 N 个元素。当您有一个非常大的集合并且对以下内容感兴趣时,这往往很有用:基于某些排序谓词的第一个元素之一。
据我所知,.NET BCL 或 LINQ 扩展都没有提供等效的功能。所有排序方法(包括 Enumerable.OrderBy)都执行集合的完整排序。
如果您需要 Nth 的高效版本,则需要在 IEnumerable 上推出自己的扩展方法来实现此目的。如果您打算自行推出,您可能需要研究快速选择算法,该算法具有 O(n) 性能。
如果暴力破解版本足够了,您可以使用 LINQ:
I presume you are looking for an accessor that returns the Nth element of an unordered collection by performing a partial-sort on the collection. This tends to be useful when you have a very large collection and are interested in one of the first elements based on some ordering predicate.
To my knowledge, neither the .NET BCL or LINQ extensions offer an equivalent. All of the sorting methods (including Enumerable.OrderBy) perform a complete ordering of the collection.
If you need an efficient version of Nth, you will need to roll your own extension method on IEnumerable to do so. If you are going to roll you own you may want to look into the Quick Select algorithm, which has O(n) performance.
If the brute-force version is sufficient, you could use LINQ: