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;
}
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)
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With