Remove an item from an IEnumerable collection

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

    The IEnumerable interface is just that, enumerable - it doesn't provide any methods to Add or Remove or modify the list at all.

    The interface just provides a way to iterate over some items - most implementations that require enumeration will implement IEnumerable such as List

    Why don't you just use your code without the implicit cast to IEnumerable

    // Treat this like a list, not an enumerable
    List modifiedUsers = new List();
    
    foreach(var u in users)
    {
       if(u.userId != 1233)
       {
            // Use List.Add
            modifiedUsers.Add(u);
       }
    }
    

提交回复
热议问题