I have a popuplated IEnumerable<User>
collection.
I want to remove an item from it, how can I do this?
foreach(var u in users) { if(u.userId = 1123) { // remove! } }
I know your not suppose to remove while looping, so I don't mind either creating a new collection or removing it after.
But I don't know how to remove an item, kind of lost for some reason on this!
Alternately which I am confused on also, how can I create a new collection like:
IEnumerable<User> modifiedUsers = new List<User>(); foreach(var u in users) { if(u.userId != 1233) { modifiedUsers.add ?????? } }
How can I add to the collection?
Clear() will empty out an existing IEnumerable. model. Categories = new IEnumerable<whatever>() will create a new empty one. It may not be a nullable type - that would explain why it can't be set to null.
What you can do is use the Add extension method to create a new IEnumerable<T> with the added value. var items = new string[]{"foo"}; var temp = items; items = items. Add("bar");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With