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: