Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashSet not removing an item

Tags:

c#

hashset

Im not sure what the problem here is,

i got a HashSet<object> called _itemsToProcess.

Eventually in my code (no multitrheading) i want to remove items from the hashset

_itemsToProcess.Remove(item);

This doesnt work. I also tried

_itemsToProcess.RemoveWhere(i=>i.Equals(item));

Well it looks trivial, but i can guarantee, item is inside _itemsToProcess. I checked in debugging via

_itemsToProcess.Any(item.Equals) // Returns true
_itemsToProcess.Contains(item)   // Returns false

item.GetHashcode() == _itemsToProcess.First().GetHashcode()  // returns true aswell.

The item doesnt implement ICompareable nor IEquatable so im out of ideas here.

Example (Simplified alot, since this is kind of a big thing)

readonly _itemsToProcess = new HashSet<object>();

void getItems()
{
    foreach(object o in getObjects())
         if(meetsCriteria(o)) _itemsToProcess.Add(o);

}



void processItems()
{
   if(_itemsToProcess.Count> 0)
   { 
      foreach(object item in _itemsToProcess.Where(criteria).ToArray())
          processItem(item);
   }
}

// This gets called in different ways
void processItem(object item)
{ 
     ... do stuff
     if(succes)
         _itemsToProcess.Remove(item);
}

So Rephrasing the problem

var compare = _itemsToProcess.First();
compare.GetHashcode() == item.GerHashcode() // true
compare.Equals(item) // true

_itemsToProcess.Contains(item)  // false, why?
like image 386
CSharpie Avatar asked Feb 21 '14 16:02

CSharpie


1 Answers

So the answer is:

when the item was added to the Hashset, the GetHashcode returned a different value. Since the processing seemed to change a propertie that was taken into account in that method, the gethashcode returned a different value at the end.

So this explains why even contains didnt work.

Thank you for your help.

like image 62
CSharpie Avatar answered Oct 04 '22 21:10

CSharpie