Remove an item from an IEnumerable collection

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

    Try turning the IEnumerable into a List. From this point on you will be able to use List's Remove method to remove items.

    To pass it as a param to the Remove method using Linq you can get the item by the following methods:

    • users.Single(x => x.userId == 1123)
    • users.First(x => x.userId == 1123)

    The code is as follows:

    users = users.ToList(); // Get IEnumerable as List
    
    users.Remove(users.First(x => x.userId == 1123)); // Remove item
    
    // Finished
    

提交回复
热议问题