Remove an item from an IEnumerable collection

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

    You can't remove IEnumerable<T> elements, but you can use the Enumerable.Skip Method

    0 讨论(0)
  • 2020-12-09 08:04

    You can't. IEnumerable<T> 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);
       }
    }
    
    0 讨论(0)
  • 2020-12-09 08:07

    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();
    
    0 讨论(0)
提交回复
热议问题