C# 是否有等效的 std::nth_element ?

发布于 08-26 15:05 字数 184 浏览 13 评论 0原文

我正在将一些 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

避讳2024-09-02 15:05:50

我假设您正在寻找一个访问器,通过对集合执行部分排序来返回无序集合的第 N 个元素。当您有一个非常大的集合并且对以下内容感兴趣时,这往往很有用:基于某些排序谓词的第一个元素之一。

据我所知,.NET BCL 或 LINQ 扩展都没有提供等效的功能。所有排序方法(包括 Enumerable.OrderBy)都执行集合的完整排序。

如果您需要 Nth 的高效版本,则需要在 IEnumerable 上推出自己的扩展方法来实现此目的。如果您打算自行推出,您可能需要研究快速选择算法,该算法具有 O(n) 性能。

如果暴力破解版本足够了,您可以使用 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(n - 1).First();
    }
}

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:

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(n - 1).First();
    }
}
迟到的我2024-09-02 15:05:50

不,事实并非如此。您必须手动编写选择算法(最好是快速选择)。

No, it doesn't. You'll have to write the selection algorithm (preferrably quick select) by hand.

第七度阳光i2024-09-02 15:05:50

没有直接的等价物。您可以使用 LINQ 的 OrderBy 和 Take/Skip 在任何 IEnumerable 上实现相同的目标,但整个集合将在此过程中进行排序。

There isn't a direct equivalent. You could, potentially, use LINQ's OrderBy and Take/Skip to acheive the same goals on any IEnumerable, but the entire collection will get sorted in this process.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文