I have a HashSet<MyCustomClass> mySet = new HashSet<MyCustomClass>(); and I wish to remove all MyCustomClass’s that contain the same values.
Let’s say MyCustomClass looks like this:
public class MyCustomClass
{
Point point;
public MyCustomClass(int x, int y)
{
point.X = x;
point.Y = y;
}
// Other methods...
}
I tried to implement IEqualityComparer like MSDN suggests, and pass it through the constructor of the HashSet<MyCustomClass>(); but I ended up unsuccessfully.
What’s the correct approach?
EDIT:
This is my Chain class and my ChainEqualityComparer:
public class Chain
{
HashSet<Mark> chain;
HashSet<Mark> marks;
public Chain(HashSet<Mark> marks)
{
chain = new HashSet<Mark>();
this.marks = marks;
}
// Other methods...
}
public class ChainEqualityComparer : IEqualityComparer<Chain>
{
#region IEqualityComparer<Chain> Members
public bool Equals(Chain x, Chain y)
{
if (x.ChainWithMarks.Count == y.ChainWithMarks.Count)
{
foreach (Mark mark in x.ChainWithMarks)
{
if (!y.ChainWithMarks.Contains(mark))
return false;
}
return true;
}
return false;
}
public int GetHashCode(Chain obj)
{
return obj.GetHashCode() ^ obj.GetType().GetHashCode();
}
#endregion
}
And this is my Mark class:
public class Mark
{
int x;
int y;
public Mark(int x, int y)
{
this.x = x;
this.y = y;
}
public int X
{
get { return x; }
set { x = value; }
}
public int Y
{
get { return y; }
set { y = value; }
}
}
public class MarkEqualityComparer : IEqualityComparer<Mark>
{
#region IEqualityComparer<Mark> Members
public bool Equals(Mark x, Mark y)
{
return (x.X == y.X) && (x.Y == y.Y);
}
public int GetHashCode(Mark obj)
{
return obj.GetHashCode() ^ obj.GetType().GetHashCode();
}
#endregion
}
(I can pastebin the code if it’s too much code…)
You can use the EqualityComparer or just override Equals and GetHashCode.
You must make sure that whatever you consider to be a duplicate is identified as having an equivalent hash code, and returning true when tested for equality.
My guess is that you weren’t returning equal hash codes. Could you post the code from your equality comparer?
As a test, you could do:
A similar set of tests would be applicable to an equality comparer too.
EDIT
Yep, as suspected it’s the hash code function. You need to calculate it based on the values of the type itself. A common enough mistake.
That assumes
pointis the only state field in your type.