Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove an item from an IEnumerable<T> collection

Tags:

c#

ienumerable

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?

like image 400
loyalflow Avatar asked Jan 03 '13 16:01

loyalflow


People also ask

How do I empty my IEnumerable?

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.

How do I add to IEnumerable?

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");


2 Answers

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(); 
like image 110
lante Avatar answered Sep 20 '22 00:09

lante


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.

like image 37
Willem D'Haeseleer Avatar answered Sep 19 '22 00:09

Willem D'Haeseleer