Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find and Remove from IList

I have a IList of users

private IList<User> _Players

I have a method to remove a specific user from the list

public virtual void RemovePlayer(User User)
{
    int index=_Players.Select(T=>T.ID).ToList().IndexOf(User.ID);
    _Players.RemoveAt(index);
}

I would like to know if there is a simpler way to remove a user from this list

like image 336
David Avatar asked Apr 09 '11 20:04

David


2 Answers

How about this? Use this if your parameter User is not part of _Players.

 _Players.Remove(_Players.SingleOrDefault(x => x.ID == User.ID));

The SingleOrDefault() ensures that if the match is not found, that null is returned. When trying to remove null, no err occurs or is thrown.

like image 149
p.campbell Avatar answered Sep 30 '22 04:09

p.campbell


If the User objects you use are held within the _Players list (same object references) you can just do

_Players.Remove(user);

Otherwise if only the id matches you can do:

_Players.RemoveAll( p => p.ID == user.ID);
like image 39
BrokenGlass Avatar answered Sep 30 '22 04:09

BrokenGlass