Find and remove from IList

I have IList users

private IList<User> _Players 

I have a way 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 an easier way to remove a user from this list

+6
source share
5 answers

There are two scenarios, the user variable that you pass to RemovePlayer

  • really contained in your list
  • has the same ID value, but is not the same object.

From your sample code you cannot say.

In the first case, just call _Players.Remove(user) . For the second case, run the System.IEquatable<User> user interface to determine the default value of EqualityComparer<User> , and then call _Players.Remove(user) again. This second scenario works in both cases.

+4
source

If the User objects you use are stored in the _ Players list (same object references), you can simply do

 _Players.Remove(user); 

Otherwise, if you can only do an identifier:

 _Players.RemoveAll( p => p.ID == user.ID); 
+11
source

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

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

SingleOrDefault() ensures that if no match is found, this null is returned. When you try to remove null, the error does not occur or does not occur.

+8
source

Depends, if you have implemented IEquatable for your user for comparison using ID , then you can just do _Players.Remove(user) .

Otherwise:

 var doomed = _Players.FirstOrDefault(p => p.ID == user.ID); if (doomed != null) _Players.Remove(doomed); 
+3
source

Only if you have List<T> :

All mentioned algorithms with SingleOrDefault() / FirstOrDefault() require two passes among the list:

1) first find the item by criteria

2) the second, to find the index of the element by its value found in step # 1

It will be more effective than this:

 int index = list.FindIndex(i => criteria); if (index >= 0) list.RemoveAt(index); 
+1
source

Source: https://habr.com/ru/post/885576/


All Articles