Abdulsalam Elsharif
Abdulsalam Elsharif

Reputation: 5101

How to delete relational rows in WPF?

I have Two table (Invoices-Receipts), every invoice have more than receipt (one to many relation)

In WPF if I want To delete all Receipts for a specific Invoice in one step, How can I do that ?

I have tried this:

     foreach (var item in _invoice.Receipts)
        _invoice.Receipts.Remove(item);

but it didn't work :(

Thank you in advance.

Upvotes: 1

Views: 48

Answers (1)

Alberto Solano
Alberto Solano

Reputation: 8227

You can't delete an item from Receipts collection (is it a List<Receipts> ?) while you're enumerating it. For this reason, your code doesn't work.

Create a collection of the items you want to remove in this way:

var itemsToRemove = new List<Receipts>();

foreach (var item in _invoice.Receipts)
{
   if(condition)
   {
       itemsToRemove.Add(item);
   }
}

and then use the RemoveAll() method to remove them from your _invoice.Receipts:

_invoice.Receipts.RemoveAll(x => itemsToRemove.Contains(x));

Upvotes: 2

Related Questions