How do I update a single item in an ObservableCollection class?

xarzu picture xarzu · Jul 21, 2011 · Viewed 71.5k times · Source

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>

Answer

Kirill Polishchuk picture Kirill Polishchuk · Jul 21, 2011

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.