When working with HashSets
in C #, I recently encountered an annoying problem: HashSets
does not guarantee the uniqueness of elements; they are not sets. They ensure that when calling Add(T item)
item is not added if for any item in the set item.equals(that)
is true
. This no longer works if you are manipulating elements already set in the set. A small program that demonstrates (copypasta from my Linqpad):
void Main() { HashSet<Tester> testset = new HashSet<Tester>(); testset.Add(new Tester(1)); testset.Add(new Tester(2)); foreach(Tester tester in testset){ tester.Dump(); } foreach(Tester tester in testset){ tester.myint = 3; } foreach(Tester tester in testset){ tester.Dump(); } HashSet<Tester> secondhashset = new HashSet<Tester>(testset); foreach(Tester tester in secondhashset){ tester.Dump(); } } class Tester{ public int myint; public Tester(int i){ this.myint = i; } public override bool Equals(object o){ if (o== null) return false; Tester that = o as Tester; if (that == null) return false; return (this.myint == that.myint); } public override int GetHashCode(){ return this.myint; } public override string ToString(){ return this.myint.ToString(); } }
He will be happy to manipulate the elements in the collection equal, only filtering them when creating a new HashSet. What is recommended when I want to work with sets where I need to know that the records are unique? Turn over my own, where does the Add (T) element add a copy from the element, and the enumeration lists the copies of the contained elements? This presents a problem in that each containing element must be deeply copied, at least in its elements, which affect its equality.
Another solution would be to collapse your own and take only elements that implement INotifyPropertyChanged and take action on this event to re-check for equality, but this seems to be very limiting, not to mention the big work and performance loss under the hood .
Another possible solution that I was thinking about is to make sure that all fields in readorly or const are constructive. All solutions have very big disadvantages. Do I have other options?
source share