CrazyWu
CrazyWu

Reputation: 687

Custom comparison of HashSets

I'm trying to create a custom comparer for my class:

using System.Collections.Generic;

namespace i.changed.namespaces.DataStructures
{
public class Edge
{
    public Cords startPoint, endPont;
    public double length;

    //more code here that doesnt matter
}

public class EdgeComparer : IEqualityComparer<Edge>
{
    public bool Equals(Edge x, Edge y)
    {
        //Check whether the objects are the same object. 
        if (x.Equals(y)) return true;

        return x.startPoint.Equals(y.startPoint) && x.endPont.Equals(y.endPont) && (x.length - y.length < 0.0001);

    }

    public int GetHashCode(Edge obj)
    {
        int hash = 17;
        hash = hash * 23 + obj.length.GetHashCode();
        hash = hash * 23 + obj.startPoint.GetHashCode();
        hash = hash *23 + obj.endPont.GetHashCode();

        return hash;
    }
}

}

I'm using this class in another object:

using i.changed.namespaces.DataStructures;
namespace i.changed.namespaces
public class MyClass
{
   HashSet<Edge> Edges, NewEdges;
   public MyClass()
   {
      NewEdges = new HashSet<Edge>();
      Edges = new HashSet<Edge>();
   }

and at some point I want to get a union of this hashsets:

newEdges.UnionWith(Edges);

but it looks like it's never using my EdgeComparer this way. What am I doing wrong?

Upvotes: 4

Views: 3510

Answers (1)

Johnny
Johnny

Reputation: 9519

HashSet<T> provides constructor where you can pass your custom implementation of the IEqualityComparer<T>. If you pass it, then it will be used otherwise HashSet<T> will be constructed using default IEqualityComparer<T>.

The solution for your problem is to modify your code slightly and pass your EdgeComparer into the HasSet<Edge> constructor

public MyClass()
{
    NewEdges = new HashSet<Edge>(new EdgeComparer());
    Edges = new HashSet<Edge>(new EdgeComparer());
}

Upvotes: 7

Related Questions