如何从名单中删除其中一个对象; T&GT;在C#中,并返回被删除的对象呢? [英] How to remove an object from List<T> in C# and return the removed object?
问题描述
如何删除的对象名单,其中,T&gt;在C#和返回删除对象
确实 RemoveAt
销毁的对象?
我是否需要先进行对象的深层副本,然后调用 RemoveAt
?
Does RemoveAt
destroys the object?
Do I need to first make deep copy of the object and then call RemoveAt
?
推荐答案
RemoveAt不破坏对象和深拷贝将不再需要。
RemoveAt does not destroy the object and a deep copy will not be needed.
var result = list[i];
list.RemoveAt(i);
return result;
RemoveAt
是O( N 的 - 的我的)VS 删除
这是O( N 的)(其中的 N 的是长的我的是要删除的元素的索引)。当你删除一个元素,你必须后移都记录下来的。
RemoveAt
is O(n - i) vs Remove
which is O(n) (where n is the length and i is the index of the element to be removed). After you've removed an element, you have to shift everything after it down one.
根据这个文件,如果你想移除元素的最高效的方式,将其交换与去年,元素,然后删除。这不保持像上述的顺序。在理论上,这意味着它是O(1)以除去列表的最后一个元素
According to this documentation, if you want the most performant way of removing an element, swap it with last, element and then remove that. This does not maintain the order like the above. In theory this means that it is O(1) to remove the last element of a list.
var result = list[i];
list[i] = list[list.Length-1];
list.RemoveAt(list.Length-1);
return result;
这篇关于如何从名单中删除其中一个对象; T&GT;在C#中,并返回被删除的对象呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!