Remove one Item in ObservableCollection

.net, c#, wpf

Solution

Your problem is that you are trying to remove an object from the collection that is not in that collection. It might have the same property values, but it is not the same object. There is a simple 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 are getting the actual item from the collection and then passing that into the `Remove` method.

Problem

I have some method like: ``` public void RemoveItem(ObservableCollection<SomeClass> collection, SomeClass instance) { if(collection.Contains(instance)) { collection.Remove(instance); } } ``` First, even the collection contains the instance, the `if` sentence still return `false`. Second, I delete the if sentence, just make the collection can remove the instance. And after the execution the collection still kept its original items, which still include instance. Is it the Reference problem, but how to fix it? I just want to remove one item from the ObservableCollection and keep its Observable functionality (which puzzled me here).

Original source