Remove an item from an IEnumerable collection

后端 未结 9 1809
死守一世寂寞
死守一世寂寞 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 08:04

    You can't. IEnumerable 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);
       }
    }
    

提交回复
热议问题