Remove object from generic list by id

前端 未结 6 1425
你的背包
你的背包 2021-02-07 10:50

I have a domain class like this:

public class DomainClass
{
  public virtual string name{get;set;}
  public virtual IList Notes{get;set;}
}
         


        
6条回答
  •  再見小時候
    2021-02-07 11:54

    You can either code it manually. The naive implementation is O(n*k) with n the number of items in the list, and k the number of items you want to remove. If you want to just remove a single item it is fast.

    But if you want to remove many items then the native implementation becomes O(n^2) for many IList implementations(including List, no idea how NHibernate's list behaves) and you need to write a bit more code to get a O(n) RemoveAll implementation.

    One possible implementation from an old answer: List, not lose the reference

    The trick with this implementation is that in moves the kept items to the beginning of the list in O(n). Then it keeps removing the last item of the list(which is usually O(1) since no elements need to move), so the truncation becomes O(n) total. This means the whole algorithm is O(n).

提交回复
热议问题