C# 相当于 std::sort 和 std::unique

标签 c# .net sorting unique

我在 C# 中有一个整数列表。我想删除重复项。 在 C++ 中,我会通过 std::sort 和 std::unique 算法运行它,以一种非常有效的方式获取唯一列表。

在 C# 中执行相同操作的最佳方法是什么?换句话说,我正在寻找一种更优雅的方式来执行以下代码:

    private static int[] unique(int[] ids)
    {
        IDictionary<int, object> d = new Dictionary<int, object>();
        foreach(int i in ids)
            d[i] = null;

        int[] results = new int[d.Count];
        int j = 0;
        foreach(int id in d.Keys)
            results[j++] = id;

        return results;
    }

最佳答案

您使用的是什么版本的 .NET?

在 .NET 3.5 中这就像调用 Distinct() 一样简单扩展方法然后ToArray()如果你真的又需要一个数组。

例如:

int[] x = new[] { 1, 4, 23, 4, 1 };
int[] distinct = x.Distinct().ToArray();
// distinct is now { 1, 4, 23 } (but not necessarily in that order)

关于C# 相当于 std::sort 和 std::unique,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/265208/

相关文章:

c# - 十进制到字符串 "Specified cast is not valid"

c# - 可以在 C# 中使用数组 ['Name' ] 访问的数组

c# - 从 HTML 字符串中删除所有内联样式和(大多数)类

c# - 类中的 AutoFixture 设置界面属性

具有 SQL Server 数据库连接的 ASP.Net 网络服务

c# - 如何在 ItemsControl 中实现自定义内联搜索?

c# - 在C#中查找较大字符串中子字符串的所有位置

c++ - 数组排序

c++ - 我如何对对象进行排序?

arrays - 从由任意两个或多个连续自然数相乘形成的排序数组中查找第 N 个数字