Remove an item from an IEnumerable<T> collection
Not removing but creating a new List
without that element with LINQ:
// remove
users = users.Where(u => u.userId != 123).ToList();
// new list
var modified = users.Where(u => u.userId == 123).ToList();
You can not remove an item from an IEnumerable
; it can only be enumerated, as described here:
http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspx
You have to use an ICollection
if you want to add and remove items. Maybe you can try and casting your IEnumerable
; this will off course only work if the underlying object implements ICollection`.
See here for more on ICollection
:
http://msdn.microsoft.com/en-us/library/92t2ye13.aspx
You can, of course, just create a new list from your IEnumerable, as pointed out by lante, but this might be "sub optimal", depending on your actual use case, of course.
ICollection
is probably the way to go.
Try turning the IEnumerable
into a List
. From this point on you will be able to use List
's Remove
method to remove items.
To pass it as a param to the Remove
method using Linq you can get the item by the following methods:
-
users.Single(x => x.userId == 1123)
users.First(x => x.userId == 1123)
The code is as follows:
users = users.ToList(); // Get IEnumerable as List
users.Remove(users.First(x => x.userId == 1123)); // Remove item
// Finished
You can't. IEnumerable<T>
can only be iterated.
In your second example, you can remove from original collection by iterating over a copy of it
foreach(var u in users.ToArray()) // ToArray creates a copy
{
if(u.userId != 1233)
{
users.Remove(u);
}
}
You can do something like this:
users = users.Where(x => x.userId != userIdToRemove);