Using LINQ to remove an item from an ObservableCollection source

Actually, this is a closer duplicate:
RemoveAll for ObservableCollections?

Possible duplicate:
using LINQ to delete objects in the <T> list
Strike>

This is the code I use, but not very readable. Can I use LINQ to shorten the code below while having the same features?

int index = 0; int pos = 0; foreach (var x in HomeViewModel.RecentPatients) { if (x.PID == p.PID) pos = index; else index++; } HomeViewModel.RecentPatients.RemoveAt(pos); 
+4
source share
2 answers

Apologies for the confusion of duplicate closures. This question and the highlighted answer will allow you to support an extension method to remove from observable collections:

RemoveAll for ObservableCollections?

It will not support the syntax from x in y , but it will allow you to:

 var c = new ObservableCollection<SelectableItem>(); c.Remove(x => x.IsSelected); 

However, with checking x.PID == p.PID and a note about your other question ... If you really want to delete items that are in both lists, this might not be the best option.

Except extension method will enumerate items that exclude items that are listed in the argument, in your case a second list. This method does not mutate the existing enumeration, like most actions, it returns a new one, so you will need to set it to a new ObservableCollection .

+3
source

You can try this.

 var toRemove = HomeViewModel.RecentPatients.Where(x=>x.PID == pid).ToList(); foreach (var item in toRemove) HomeViewModel.RecentPatients.Remove(item); 
+3
source

All Articles