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

Pau*_*rth 4 .net c# 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;
    }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 8

您使用的是什么版本的.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)
Run Code Online (Sandbox Code Playgroud)