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); 
5
  • @Adam Houldsworth that is from a List<t>, I specified ObservableCollection Source. Commented Jul 16, 2012 at 8:23
  • how is this different from your previous question? stackoverflow.com/q/11498056/201088 Commented Jul 16, 2012 at 8:23
  • @SupaOden I noticed, but I cannot redact close votes. Only vote to reopen if it closes. Apologies. Commented Jul 16, 2012 at 8:25
  • Saying that, it is more of a duplicate of stackoverflow.com/questions/5118513/… Commented Jul 16, 2012 at 9:04
  • The best way to this is HomeViewModel.RecentPatients.Where(p => ... ).ToList().All(i => HomeViewModel.RecentPatients.Remove(i)); Commented Dec 10, 2018 at 8:20

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

4

You can try this.

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

2 Comments

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;}
Even with the ToList() in there?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.