我在 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/