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).