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

I have a list of integers in C #. I want to remove duplicates. In C ++, I ran it through std :: sort and then std :: unique algorithms for a very efficient way to get a unique list.

What is the best way to do the same 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; } 
+4
source share
7 answers

What version of .NET are you using?

In .NET 3.5, it is as simple as calling the Distinct () method and then ToArray () if you really need an array again.

For instance:

 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) 
+8
source

if you consider STL methods to be "very efficient", so use the 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 equivalent 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); }); 
+3
source

Even with .NET 2.0, you can get the same with LINQBridge . It will be easier to use with C # 3.0 (even with .NET 2.0), but should be used with C # 2.0 and .NET 2.0 - you just need to use Enumerable.Distinct (x), not x.Distinct ();

Of course, in the end, these are just pre-wrapped versions of the code that you published earlier (give or receive things like iterator blocks), so you can simply paste this code into the utility class and (re) use it from there.

+1
source

Alas, I only have .NET 2.0 to work with

0
source

On a side note, C # has a static System.Array.Sort method that you can use to sort real arrays without using a collection.

0
source

I don’t know how big your collection is, but if you are not dealing with thousands of integers, this might be good enough:

 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; } } } 
0
source
  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; } 
0
source

All Articles