且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

列表如何删除项目?

更新时间:2023-12-05 15:27:28

在此处进行解释 http://msdn.microsoft.com/zh-CN/library/6sh2ey19.aspx [ ^ ]表示

列表< T>的容量;是List< T>所包含元素的数量.能把持住.当将元素添加到List< T>时,通过重新分配内部数组,容量会根据需要自动增加.
如果可以估计集合的大小,则使用List< T>(Int32)构造函数并指定初始容量可以消除在将元素添加到List< T>时执行大量调整大小操作的需要.
可以通过调用TrimExcess方法或显式设置Capacity属性来减少容量.减少容量会重新分配内存并复制List< T>中的所有元素.
此构造函数是O(1)操作.


并在此处进行了说明 http://msdn.microsoft.com/en-us/library/cd666k3e#Y0 [ ^ ]表示

List.Remove方法使用默认的相等比较器EqualityComparer< T>确定相等性.T的默认值是列表中值的类型.

该方法执行线性搜索;因此,此方法是O(n)运算,其中n是Count.


从以上两个参考文献中可以看出,List<T>实现了array internally,而Remove method使用linear search删除了找到的first element.
It is explained here http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx[^] that

The capacity of a List<T> is the number of elements that the List<T> can hold. As elements are added to a List<T>, the capacity is automatically increased as required by reallocating the internal array.

If the size of the collection can be estimated, using the List<T>(Int32) constructor and specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the List<T>.

The capacity can be decreased by calling the TrimExcess method or by setting the Capacity property explicitly. Decreasing the capacity reallocates memory and copies all the elements in the List<T>.

This constructor is an O(1) operation.


And it is explained here http://msdn.microsoft.com/en-us/library/cd666k3e#Y0[^] that

List.Remove method determines equality using the default equality comparer EqualityComparer<T>.Default for T, the type of values in the list.

This method performs a linear search; therefore, this method is an O(n) operation, where n is Count.


From the above two references it can be seen that the List<T> implements an array internally and the Remove method uses linear search to remove the first element found.