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
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With