IObservableCollection<T> question

Topics: Actions & Coroutines
Feb 22, 2012 at 2:31 PM

I have:

IObservableCollection<MishMash> Stuffs { get; set; }  (using NotifyPropertyChanged(...) in the set to indicate change in Stuffs)

private IObservableCollection<MishMash> _stuffs; 
public IObservableCollection<MishMash> Stuffs 
{
    get { return _stuffs; }
    set 
    {
        _stuffs = value;
        NotifyPropertyChange(()=>Stuffs);
    }
}

 

This populates a grid which gets edited... and when the user clicks the save button, the Save method saves off those changes made to the rows in the grid.  I want the grid to reflect the saved changes by removing the edited rows.  The grid should then show only unedited rows.  No biggie...?

public void Save()
{
    var editedRecs = Stuffs.Where( r => !string.IsNullOrEmpty(r.SomeField));
    
    foreach(MishMash mmRecord in editedRecs)
     {
         //...blah blah save this mmRecord

         RemoveItem(mmRecord);
     }
}

private void RemoveItem(MishMash item)
{
     if (item == null) return;
     Stuffs.Remove(item);
     Stuffs.Refresh();
}

 

So in my grid I have 20 records... I edit 3 rows... click save and in a perfect world the 3 rows I edited would be removed from the grid, however

I get an error in the foreach loop stating that the collection has changed..."Collection was modified; enumeration operation may not execute."

How can I remove the item from the colleciton so that the grid will reflect the change?  

 

 

Feb 22, 2012 at 2:38 PM

You cannot modify a collection which is being enumerated.

The following code

Stuffs.Where( r => !string.IsNullOrEmpty(r.SomeField))

does not create a new collection, but provides a special enumerator visiting the Stuffs list.

Change that code to

Stuffs.Where( r => !string.IsNullOrEmpty(r.SomeField)).ToList()
to create a new collection to enumerate, this way no problem should occur.

Feb 22, 2012 at 2:43 PM

thanks Blade... yeah (as it always happens....) about 40 secs after I posted that occured to me ... it works :) thanks for the reply!