nichu09
nichu09

Reputation: 892

Remove multiple items from observablecollection in silverlight

how can i remove multiple items from observablecollection in silverlight.in my project i have one datagrid populating more than one items.in every row contain one checkbox also.if i select more than one row by selecting checkbox and click delete button ,i want to delete all the item from the collection.

public void delete(object parameter)
    {
      foreach (var x in Book)
        {
              if (x.Ischeck == true)
                 {
                    Book.Remove(x);
                  }
         }
     } 

it cause error.can't change observablecollection

Upvotes: 3

Views: 18482

Answers (3)

Furqan Safdar
Furqan Safdar

Reputation: 16698

You can use below mentioned code snippet instead:

foreach (var x in Book.ToList())
{
    if (x.Ischeck)
    {
        Book.Remove(x);
    }
}

OR

for (int i = Book.Count - 1; i >= 0; i--)
{
    if (Book[i].Ischeck)
    {
        Book.RemoveAt(i);
    }
}

Upvotes: 16

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174299

I assume that the error message is a bit different. To be more precise, it is:

Collection was modified; enumeration operation may not execute.

To work around this problem, one possible solution is this:

foreach (var itemToRemove in Book.Where(x => x.Ischeck).ToList())
{
    Book.Remove(itemToRemove);
}

This will get all items you want to remove and put them into a new list. When you now remove items from Book you are not disturbing the list you are currently iterating over as this is an independent instance.

Using Where before calling ToList reduces the number of references you copy to the new list to only those that really need to be copied.

Upvotes: 6

user1793714
user1793714

Reputation: 329

Simply get a list of the objects contained first:

public void delete(object parameter)
{
    foreach (var x in Book.ToList())
    {
        if (x.Ischeck == true)
        {
            Book.Remove(x);
        }
    }
} 

The reason for this is that you can't remove elements from an observable collection while you're enumerating the elements. By calling ToList() you enumerate the whole collection first, store it in a list and then check what to remove.

Upvotes: 1

Related Questions