6

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); 
Community
  • 1
  • 1
SupaOden
  • 722
  • 4
  • 13
  • 41

2 Answers2

5

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.

Community
  • 1
  • 1
Adam Houldsworth
  • 63,413
  • 11
  • 150
  • 187
4

You can try this.

var toRemove = HomeViewModel.RecentPatients.Where(x=>x.PID == pid).ToList();
foreach (var item in toRemove)
    HomeViewModel.RecentPatients.Remove(item);
Yograj Gupta
  • 9,811
  • 3
  • 29
  • 48
  • 2
    With this code you should try to remove only one row from the collection. More than that we will get the following exception "Collection was modified; enumeration operation may not execute." So break the for each loop after first execution or copy to a new collection.foreach (var item in toRemove) { HomeViewModel.RecentPatients.Remove(item); break;} – Ananda Apr 10 '14 at 10:29
  • Even with the ToList() in there? – Jasper Jun 21 '16 at 19:46