Actually, it is a closer duplicate of:
RemoveAll for ObservableCollections?
Possible Duplicate:
using LINQ to remove objects within a List<T>
This is the code I'm using, but its not very readable. Can I use LINQ to shorten the code below while still having the same functionality?
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);
Apologies for the duplicate closure confusion. This question and marked answer will let you have extension method support for removing from observable collections:
RemoveAll for ObservableCollections?
It won't give support for the from x in y
syntax, but it will let you do:
var c = new ObservableCollection<SelectableItem>();
c.Remove(x => x.IsSelected);
However, with the check x.PID == p.PID
and the note about your other question... If in fact you want to remove items that are in both lists, this might not be the best option.
The Except
extension method will produce an enumerable of items that exclude items that are in the enumerable provided as an argument, in your case the second list. This method doesn't mutate the existing enumerable, like most actions it returns a new one, so you would need to set that into a new ObservableCollection
.
You can try this.
var toRemove = HomeViewModel.RecentPatients.Where(x=>x.PID == pid).ToList();
foreach (var item in toRemove)
HomeViewModel.RecentPatients.Remove(item);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With