Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting List of Objects that occurs exaclty twice in a list

Tags:

c#

duplicates

I have a List<CustomPoint> points; which contains close to million objects. From this list I would like to get the List of objects that are occuring exactly twice. What would be the fastest way to do this? I would also be interested in a non-Linq option also since I might have to do this in C++ also.

public class CustomPoint
{
    public double X { get; set; }
    public double Y { get; set; }

    public CustomPoint(double x, double y)
    {
        this.X = x;
        this.Y = y;
    }
}

public class PointComparer : IEqualityComparer<CustomPoint>
{
    public bool Equals(CustomPoint x, CustomPoint y)
    {
        return ((x.X == y.X) && (y.Y == x.Y));
    }

    public int GetHashCode(CustomPoint obj)
    {
        int hash = 0;
        hash ^= obj.X.GetHashCode();
        hash ^= obj.Y.GetHashCode();
        return hash;
    }
}

based on this answer, i tried,

list.GroupBy(x => x).Where(x => x.Count() = 2).Select(x => x.Key).ToList(); 

but this is giving zero objects in the new list. Can someone guide me on this?

like image 820
vinayan Avatar asked Dec 20 '12 11:12

vinayan


1 Answers

You should implement Equals and GetHashCode in the class itself and not in the PointComparer

like image 127
Sawan Avatar answered Nov 01 '22 15:11

Sawan