code_junkie

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

Nov 12th, 2011
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. private static int[] unique(int[] ids)
  2. {
  3. IDictionary<int, object> d = new Dictionary<int, object>();
  4. foreach(int i in ids)
  5. d[i] = null;
  6.  
  7. int[] results = new int[d.Count];
  8. int j = 0;
  9. foreach(int id in d.Keys)
  10. results[j++] = id;
  11.  
  12. return results;
  13. }
  14.  
  15. int[] x = new[] { 1, 4, 23, 4, 1 };
  16. int[] distinct = x.Distinct().ToArray();
  17. // distinct is now { 1, 4, 23 } (but not necessarily in that order)
  18.  
  19. var vals = new List<int> { 1, 2, 3, 2, 1, 2, 3, 2, 3, 4, 3, 2, 3 };
  20. vals.Sort();
  21. var uniques = new HashSet<int>(vals);
  22.  
  23. List<int> vals = new List<int>();
  24. vals.Add(1);
  25. vals.Add(2);
  26. vals.Add(3);
  27. vals.Add(2);
  28. ...
  29. vals.Sort();
  30. List<int> uniques = new List<int>();
  31. vals.ForEach(delegate(int v) {
  32. if (!uniques.Contains(v)) uniques.Add(v);
  33. });
  34.  
  35. public IEnumerable<int> unique(int[] ids)
  36. {
  37. List<int> l = new List<int>();
  38. foreach (int id in ids)
  39. {
  40. if (!l.Contains(id))
  41. {
  42. l.Add(id);
  43. yield return id;
  44. }
  45. }
  46. }
  47.  
  48. private static List<T> GetUnique<T>(List<T> list) where T : IEquatable<T>
  49. {
  50. list.Sort();
  51. int count = list.Count;
  52. List<T> unique = new List<T>(count);
  53. T last = default(T);
  54. for (int i = 0; i < count; i++)
  55. {
  56. T val = list[i];
  57. if (i != 0 && last.Equals(val)) continue;
  58. last = val;
  59. unique.Add(val);
  60. }
  61. return unique;
  62. }
Add Comment
Please, Sign In to add comment