Possible Duplicate:
c#: how do I remove an Item inside IEnumerable
I have an Inumerable of Objects foo
.
public IEnumerable<foo> listOfFoo{ get; set; }
Foo has Id and name lets say.
I want to pass an ID to a method and the method should remove the object with that ID from the IEnumerable and return it.
Whats the best way of doing it?
IEnumerable
s are read-only. You can't remove an object from one.
That said, you could do something like
public Foo QuoteRemoveUnquoteById(int id)
{
var rtnFoo = listOfFoo.SingleOrDefault(f => f.Id == id);
if (rtnFoo != default(Foo))
{
listOfFoo = listOfFoo.Where(f => f.Id != id);
}
return rtnFoo;
}
which just masks out the matching Foo
? However, this will get less and less performant the more items you "remove". Also, anything else that holds a reference to listOfFoo
won't see any change.
That's not possible for any collection that implements IEnumerable<foo>
. If it is for example a List<foo>
, then it's possible to remove items for it, but if it is for example a foo[]
it's not possible to remove items.
If you use a List<foo>
instead:
public foo Extract(int id) {
int index = listOfFoo.FindIndex(x => x.Id == id);
foo result = listOfFoo[index];
listOfFoo.removeAt(index);
return result;
}
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