How do I update a single item in an ObservableCollection class?
I know how to do an Add. And I know how to search the ObservableCollection one item at a time in a "for" loop (using Count as a representation of the amout of items) but how do I chage an existing item. If I do a "foreach" and find which item needs updating, how to I put that back into the ObservableCollection>
You don't need to remove item, change, then add. You can simply use LINQ FirstOrDefault
method to find necessary item using appropriate predicate and change it properties, e.g.:
var item = list.FirstOrDefault(i => i.Name == "John");
if (item != null)
{
item.LastName = "Smith";
}
Removing or adding item to ObservableCollection
will generate CollectionChanged
event.
You can't generally change a collection that you're iterating through (with foreach
). The way around this is to not be iterating through it when you change it, of course. (x.Id == myId
and the LINQ FirstOrDefault
are placeholders for your criteria/search, the important part is that you've got the object and/or index of the object)
for (int i = 0; i < theCollection.Count; i++) {
if (theCollection[i].Id == myId)
theCollection[i] = newObject;
}
Or
var found = theCollection.FirstOrDefault(x=>x.Id == myId);
int i = theCollection.IndexOf(found);
theCollection[i] = newObject;
Or
var found = theCollection.FirstOrDefault(x=>x.Id == myId);
theCollection.Remove(found);
theCollection.Add(newObject);
Or
var found = theCollection.FirstOrDefault(x=>x.Id == myId);
found.SomeProperty = newValue;
If the last example will do, and what you really need to know is how to make things watching your ObservableCollection
be aware of the change, you should implement INotifyPropertyChanged
on the object's class and be sure to raise PropertyChanged
when the property you're changing changes (ideally it should be implemented on all public properties if you have the interface, but functionally of course it really only matters for ones you'll be updating).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With