## LING operation (union, intersect, except) and IEquatable<T>

26 Nov

Consider you want to use the union, intersect or except methods using the LINQ feature:

`   1: public static VoronoiCell operator +(VoronoiCell A, VoronoiCell B)`

`   2: {`

`   3:    VoronoiCell CombinedCell=new VoronoiCell();`

`   4:    var MuturalPts = A.BoundingPolygonVertices.Intersect(B.BoundingPolygonVertices);`

`   5:    if(MuturalPts==null) return null;`

`   6:    var UniqueA = A.BoundingPolygonVertices.Except(MuturalPts);`

`   7:    var UniqueB = B.BoundingPolygonVertices.Except(MuturalPts);`

`   8:    CombinedCell.BoundingPolygonVertices = UniqueA.Union(UniqueB).ToList();`

`   9:    return CombinedCell;`

`  10: }`

In order to make sure the above code works, you should indicate or define in what terms can two objects (in this case, the element of BoundingPolygonVertices, i.e. a Pt2D object). To do so, the Pt2D class should derive from IEquatable:

`   1: public class Pt2D : IEquatable<Pt2D>`

`   2:    {`

`   3:        public double X`

`   4:        { get; set;}`

`   5:        public double Y`

`   6:        { get; set;}`

`   7:  `

`   8:        public Pt2D(double a, double b)`

`   9:        {`

`  10:            X = a;`

`  11:            Y = b;`

`  12:        }`

`  13:  `

`  14:        public override bool Equals(System.Object obj)`

`  15:        {`

`  16:            if (ReferenceEquals(null, obj)) return false;`

`  17:            if (ReferenceEquals(this, obj)) return true;`

`  18:            if (obj.GetType() != typeof (Pt2D)) return false;`

`  19:            return Equals((Pt2D) obj);`

`  20:        }`

`  21:  `

`  22:        public bool Equals(Pt2D p)`

`  23:        {`

`  24:            if (ReferenceEquals(null, p)) return false;`

`  25:            if (ReferenceEquals(this, p)) return true;`

`  26:            return p.X.Equals(X) && p.Y.Equals(Y);`

`  27:        }`

`  28:  `

`  29:        public override int GetHashCode()`

`  30:        {`

`  31:            unchecked`

`  32:            {`

`  33:                return (X.GetHashCode()*397) ^ Y.GetHashCode();`

`  34:            }`

`  35:        }`

`  36:    }`

Done.