Accepted answer

It's because by using ToList you are creating new List object and then remove items form it, not from original IEnumerable.

Try using this:

alert.UserAlerts = alert.UserAlerts.Where(x => x.UserId != 2);

You can't run RemoveAll on IEnumerable, so I think using Linq here is a good idea. You will have collection of items which do not have UserId=2, which is equivalent to removing all items with UserId=2. You need to reverse your query from RemoveAll and it will work in any case.


You have to call RemoveAll on alert.UserAlerts, because ToList creates a new collection.
If you remove all items of that collection, it does not change UserAlerts.

alert.UserAlerts.RemoveAll(x => userIds.Contains(x.UserId));

If UserAlerts is not a List, use the Where extension method (as wudzik said in his answer):

alert.UserAlerts = alert.UserAlerts.Where(x => !userIds.Contains(x.UserId));


That should certainly remove the elements, but I don't see how you would even notice whether it had or not?

First you create the list with ToList() and then you call RemoveAll() to remove some elements from that list, but since you haven't stored that list anywhere, you're just going to get the number of items removed back.

Related Articles