Delete one item in ObservableCollection

I have a method like:

public void RemoveItem(ObservableCollection<SomeClass> collection, SomeClass instance) { if(collection.Contains(instance)) { collection.Remove(instance); } } 

First, even the collection contains an instance, the if clause still returns false .

Secondly, I delete the if clause, just make a collection to remove the instance. And after execution, the collection still retained its original elements, which still include a copy.

Is this a link issue, but how can I fix it? I just want to remove one element from the ObservableCollection and keep its Observable functionality ( which puzzled me here ).

+7
c # wpf
source share
3 answers

Your problem is that you are trying to remove an object from a collection that is not in this collection. It may have the same property values, but it is not the same object. There is an easy way around this if your object has a uniquely identifiable property, such as Id :

 public void RemoveItem(ObservableCollection<SomeClass> collection, SomeClass instance) { collection.Remove(collection.Where(i => i.Id == instance.Id).Single()); } 

The idea is that we get the actual item from the collection and then pass it to the Remove method.

+14
source share

If the element you are about to delete has something like a code / identifier that you can compare with another element, you can do something in the following lines:

 foreach (var item in itemSet) { if (item.ItemID == itemToCompareTo.ItemID) { itemSet.Remove(item); break; } } 
+4
source share

This seems to be a link issue. You may need to override the Equals (and GetHashCode) methods so that the ObservableCollection can find the instance, even if it is not the same reference.

The reason is that the default implementation of the Equals () method checks to see if two objects have the same reference.

Note : be careful when overriding the Equals method. You will also have to override GetHashCode, since the default implementation of the GetHashCode () method returns an integer based on the reference to the object and is not based on the values โ€‹โ€‹of the instance variables (and class) of the object.

No matter how many times the values โ€‹โ€‹of its instance variables (data fields) change, the default hash code does not change during the lifetime of the object. This is why we always implement GetHashCode () when you override the Equals () method.

More on msdn: Object.Equals Method (Object)

+2
source share

All Articles