Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# equivalent of std::sort and std::unique

I have a list of integers in C#. I wish to remove duplicates. In C++ I would run it through the std::sort and then std::unique algorithms for a very efficient way of obtaining the unique list.

What's the best way to do the same thing in C#? In other words, I'm looking for a more elegant way to do the following code:

    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;
    }
like image 363
Paul Hollingsworth Avatar asked Dec 18 '22 10:12

Paul Hollingsworth


2 Answers

What version of .NET are you using?

In .NET 3.5 that's as simple as calling the Distinct() extension method and then ToArray() if you really need an array again.

For example:

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)
like image 198
Jon Skeet Avatar answered Dec 24 '22 02:12

Jon Skeet


if you considering STL methods as "very efficient", so use following:

       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);

For 2.0 equivalent

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);
});
like image 44
Tamir Avatar answered Dec 24 '22 00:12

Tamir