DEV Community

Cover image for Removing Duplicates from an Array (Using C#)

Removing Duplicates from an Array (Using C#)

Sung M. Kim on March 18, 2017

* Featured Image – “removed.jpg” by Don Crowley, used under BY SA This article is from last year but after reading Sai's article, ...
Collapse
 
sait profile image
Sai gowtham

Do you have any solution for removing duplicate objects from an array?

Collapse
 
dance2die profile image
Sung M. Kim

I haven't implemented any but the implementation can be a bit tricky for the case 1 & 2.1

Case 1 & 2.1

  • Implement IComparable interface for instance of the class you are comparing. So that you can compare current & next objects in an array.
  • Also override the comparison operators (>, >=, <, <=).
// To enable Point class object instance comparable.
public class Point : IComparable<Point>
{
    public int CompareTo(Point otherPoint)
    {
        return this.X > otherPoint.X && this.Y > otherPoint.Y;
    }

    public static bool operator >  (Point p1, Point p2) => p1.CompareTo(p2) == 1;
    public static bool operator <  (Point p1, Point p2) => p1.CompareTo(p2) == -1;
    public static bool operator >=  (Point p1, Point p2) => p1.CompareTo(p2) >= 0;
    public static bool operator <=  (Point p1, Point p2) p1.CompareTo(p2) <= 0;
}
...

// case 1
if (a[i] != a[i + 1])
{
    result.Add(a[i]);
}

// case 2.1
if (!alreadySeen.Contains(item))
    alreadySeen.Add(item);

For Case 2.2

Create a class implementing IComparer interface so that you can specify how objects can be sorted.

public class PointComparer<Point> : IComparer<Point>
{
  int IComparer.Compare(Point p1, Point p2)  
  {
      return p1.X > p2.X && p1.Y > p2.Y;
  }
}

// ...
Array.Sort(points, new PointComparer());