Best way to remove items from a collection

前端 未结 15 2053
天命终不由人
天命终不由人 2020-12-08 05:47

What is the best way to approach removing items from a collection in C#, once the item is known, but not it\'s index. This is one way to do it, but it seems inelegant at be

15条回答
  •  醉酒成梦
    2020-12-08 06:28

    For a simple List structure the most efficient way seems to be using the Predicate RemoveAll implementation.

    Eg.

     workSpace.RoleAssignments.RemoveAll(x =>x.Member.Name == shortName);
    

    The reasons are:

    1. The Predicate/Linq RemoveAll method is implemented in List and has access to the internal array storing the actual data. It will shift the data and resize the internal array.
    2. The RemoveAt method implementation is quite slow, and will copy the entire underlying array of data into a new array. This means reverse iteration is useless for List

    If you are stuck implementing this in a the pre c# 3.0 era. You have 2 options.

    • The easily maintainable option. Copy all the matching items into a new list and and swap the underlying list.

    Eg.

    List list2 = new List() ; 
    foreach (int i in GetList())
    {
        if (!(i % 2 == 0))
        {
            list2.Add(i);
        }
    }
    list2 = list2;
    

    Or

    • The tricky slightly faster option, which involves shifting all the data in the list down when it does not match and then resizing the array.

    If you are removing stuff really frequently from a list, perhaps another structure like a HashTable (.net 1.1) or a Dictionary (.net 2.0) or a HashSet (.net 3.5) are better suited for this purpose.

提交回复
热议问题