Andikat Jacob Dennis
Andikat Jacob Dennis

Reputation: 277

I have a list that stores PointD objects. PointD is a class for storing x and y in double

How can I use the distinct method for my user defined object So that no two points are the same?


//This is my class

class PointD
{
    private double m_dPointDx;
    private double m_dPointDy;
}

This is my List that contain PointD objects

List<PointD> listPoints = new List<PointD>();
listPoints.Add(new PointD(10,45));
listPoints.Add(new PointD(20,65));
listPoints.Add(new PointD(10,45));

Now how to distinct the list so that no two points are same ?

Upvotes: 0

Views: 148

Answers (1)

Alex Filipovici
Alex Filipovici

Reputation: 32571

First, I would redefine the PointD class like this:

class PointD
{
    public double M_dPointDx;
    public double M_dPointDy;
    public PointD(double x, double y)
    {
        M_dPointDx = x;
        M_dPointDy = y;
    }
}

Define the following class which implements the IEqualityComparer<PointD> interface:

class MyComparer : IEqualityComparer<PointD>
{
    public bool Equals(PointD x, PointD y)
    {
        //Check whether the compared objects reference the same data. 
        if (Object.ReferenceEquals(x, y)) return true;

        //Check whether any of the compared objects is null. 
        if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
            return false;

        //Check whether the PointD' properties are equal. 
        return x.M_dPointDx==y.M_dPointDx && x.M_dPointDy==y.M_dPointDy;
    }

    // If Equals() returns true for a pair of objects  
    // then GetHashCode() must return the same value for these objects. 

    public int GetHashCode(PointD pointD)
    {
        //Check whether the object is null 
        if (Object.ReferenceEquals(pointD, null)) return 0;

        //Get hash code for the M_dPointDx field if it is not null. 
        int hashX = pointD.M_dPointDx == null ? 0 : pointD.M_dPointDy.GetHashCode();

        //Get hash code for the M_dPointDy field. 
        int hashY = pointD.M_dPointDy.GetHashCode();

        //Calculate the hash code for the PointD. 
        return hashX ^ hashY;
    }
}

Then, you have this usage:

List<PointD> listPoints = new List<PointD>();
listPoints.Add(new PointD(10, 45));
listPoints.Add(new PointD(20, 65));
listPoints.Add(new PointD(10, 45));

var distinctItems = listPoints
    .Distinct(new MyComparer())
    .ToList();

Upvotes: 1

Related Questions