Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I use a HashSet<MyCustomClass> to remove duplicates of MyCustomClass?
    primarykey
    data
    text
    <p>I have a <code>HashSet&lt;MyCustomClass&gt; mySet = new HashSet&lt;MyCustomClass&gt;();</code> and I wish to remove all MyCustomClass's that contain the same values. </p> <p>Let's say MyCustomClass looks like this:</p> <pre><code>public class MyCustomClass { Point point; public MyCustomClass(int x, int y) { point.X = x; point.Y = y; } // Other methods... } </code></pre> <p>I tried to implement <code>IEqualityComparer</code> like MSDN suggests, and pass it through the constructor of the <code>HashSet&lt;MyCustomClass&gt;();</code> but I ended up unsuccessfully. </p> <p>What's the correct approach?</p> <p><strong>EDIT:</strong></p> <p>This is my <code>Chain</code> class and my <code>ChainEqualityComparer</code>:</p> <pre><code>public class Chain { HashSet&lt;Mark&gt; chain; HashSet&lt;Mark&gt; marks; public Chain(HashSet&lt;Mark&gt; marks) { chain = new HashSet&lt;Mark&gt;(); this.marks = marks; } // Other methods... } public class ChainEqualityComparer : IEqualityComparer&lt;Chain&gt; { #region IEqualityComparer&lt;Chain&gt; 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 } </code></pre> <p>And this is my <code>Mark</code> class:</p> <pre><code> 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&lt;Mark&gt; { #region IEqualityComparer&lt;Mark&gt; Members public bool Equals(Mark x, Mark y) { return (x.X == y.X) &amp;&amp; (x.Y == y.Y); } public int GetHashCode(Mark obj) { return obj.GetHashCode() ^ obj.GetType().GetHashCode(); } #endregion } </code></pre> <p>(I can pastebin the code if it's too much code...)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload