Remove an item from an IEnumerable collection

后端 未结 9 1803
死守一世寂寞
死守一世寂寞 2020-12-09 07:30

I have a popuplated IEnumerable collection.

I want to remove an item from it, how can I do this?

foreach(var u in users)
{
          


        
9条回答
  •  情话喂你
    2020-12-09 07:42

    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.

提交回复
热议问题