I have a popuplated IEnumerable
collection.
I want to remove an item from it, how can I do this?
foreach(var u in users)
{
You can't remove IEnumerable<T>
elements, but you can use the Enumerable.Skip Method
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);
}
}
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();