How to Quickly Remove Items From a List

前端 未结 11 1568
情歌与酒
情歌与酒 2020-11-30 01:45

I am looking for a way to quickly remove items from a C# List. The documentation states that the List.Remove() and List.RemoveAt()<

11条回答
  •  无人及你
    2020-11-30 01:59

    If the order does not matter then there is a simple O(1) List.Remove method.

    public static class ListExt
    {
        // O(1) 
        public static void RemoveBySwap(this List list, int index)
        {
            list[index] = list[list.Count - 1];
            list.RemoveAt(list.Count - 1);
        }
    
        // O(n)
        public static void RemoveBySwap(this List list, T item)
        {
            int index = list.IndexOf(item);
            RemoveBySwap(list, index);
        }
    
        // O(n)
        public static void RemoveBySwap(this List list, Predicate predicate)
        {
            int index = list.FindIndex(predicate);
            RemoveBySwap(list, index);
        }
    }
    

    This solution is friendly for memory traversal, so even if you need to find the index first it will be very fast.

    Notes:

    • Finding the index of an item must be O(n) since the list must be unsorted.
    • Linked lists are slow on traversal, especially for large collections with long life spans.

提交回复
热议问题