Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using LINQ to delete an element from a ObservableCollection Source [duplicate]

Tags:

c#

foreach

linq

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); 
like image 927
SupaOden Avatar asked Jul 16 '12 08:07

SupaOden


2 Answers

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.

like image 144
Adam Houldsworth Avatar answered Nov 09 '22 19:11

Adam Houldsworth


You can try this.

var toRemove = HomeViewModel.RecentPatients.Where(x=>x.PID == pid).ToList();
foreach (var item in toRemove)
    HomeViewModel.RecentPatients.Remove(item);
like image 27
Yograj Gupta Avatar answered Nov 09 '22 18:11

Yograj Gupta