C#有一个std :: nth_element等效吗? [英] Does C# have a std::nth_element equivalent?
问题描述
我正在将一些C ++代码移植到C#。
I'm porting some C++ code to C#.
C#是否具有 std :: nth_element $ c>
Does C# have an equivalent to std::nth_element()
or do I need to roll my own?
推荐答案
我认为你正在寻找一个访问器返回通过对集合执行部分排序,无序集合的第N个元素。当您拥有非常大的集合,并且基于某些排序谓词对第一个元素感兴趣时,这往往是有用的。
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.
据我所知,.NET BCL或LINQ扩展都不能提供等效的。所有排序方法(包括Enumerable.OrderBy)
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.
如果你需要一个高效版本的Nth,你需要在IEnumerable上滚动自己的扩展方法。如果您要自己动手,您可能需要查看快速选择算法,其中包含
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.
如果强制版本足够,您可以使用LINQ:
If the brute-force version is sufficient, you could use LINQ:
var someCollection = new []{ 5, 2, 8, 9, 0, 1, 3, 12, 4 };
var fifthItem = someCollection.NthItem( 5 );
public static class NthExtensions {
public static T NthItem( this IEnumerable<T> coll, int n ) {
return coll.OrderBy( x => x ).Skip(m-1).First();
}
}
这篇关于C#有一个std :: nth_element等效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!