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

其他提示

如果您将STL方法视为“非常有效”,请使用以下内容:

       var vals = new List<int> { 1, 2, 3, 2, 1, 2, 3, 2, 3, 4, 3, 2, 3 };
       vals.Sort();
       var uniques = new HashSet<int>(vals);

对于2.0等值

List<int> vals = new List<int>();
vals.Add(1);
vals.Add(2);
vals.Add(3);
vals.Add(2);
...
vals.Sort();
List<int> uniques = new List<int>();
vals.ForEach(delegate(int v) {
 if (!uniques.Contains(v)) uniques.Add(v);
});

即使使用.NET 2.0,您也可以使用 LINQBridge 。这将更容易与C#3.0(即使使用.NET 2.0)一起使用,但应该可以与C#2.0和.NET 2.0一起使用 - 您只需使用Enumerable.Distinct(x)而不是x.Distinct();

当然,最终这些只是您之前发布的代码的预先包装版本(允许或者采用迭代器块之类的东西),因此您可以将该代码推送到实用程序类中并(重新)使用它那里。

唉,我只有.NET 2.0才能使用

在中途相关的说明中,C#有一个 System.Array.Sort 静态方法,可用于在不使用集合的情况下对实际数组进行排序。

我不知道你的收藏有多大,但如果你不处理成千上万的整数,这可能就足够了:

public IEnumerable<int> unique(int[] ids)
{
    List<int> l = new List<int>();
    foreach (int id in ids)
    {
        if (!l.Contains(id))
        {
            l.Add(id);
            yield return id;
        }
    }
}
  private static List<T> GetUnique<T>(List<T> list) where T : IEquatable<T>
  {
     list.Sort();
     int count = list.Count;
     List<T> unique = new List<T>(count);
     T last = default(T);
     for (int i = 0; i < count; i++)
     {
        T val = list[i];
        if (i != 0 && last.Equals(val)) continue;
        last = val;
        unique.Add(val);
     }
     return unique;
  }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top