[英]How to remove an object from List<T> in C# and return the removed object?
How to remove an object from List<T>
in C# and return the removed object ? 如何从C#中的List<T>
中删除一个对象并返回被删除的对象?
Does RemoveAt
destroys the object? RemoveAt
是否会破坏对象? 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. RemoveAt不会破坏对象,也不需要深层副本。
var result = list[i];
list.RemoveAt(i);
return result;
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). RemoveAt
是O( n - i )vs Remove
,它是O( n )(其中n是长度, i是要删除的元素的索引)。 After you've removed an element, you have to shift everything after it down one. 删除元素后,必须将其后的所有元素都移除。
According to this documentation, if you want the most performant way of removing an element, swap it with last, element and then remove that. 根据此文档,如果您想要以最高效的方式删除元素,请将其与last,element交换,然后将其删除。 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. 从理论上讲,这意味着删除列表的最后一个元素是O(1)。
var result = list[i];
list[i] = list[list.Length-1];
list.RemoveAt(list.Length-1);
return result;
You could do: 你可以这样做:
var listObject = list.ElementAt(index);
list.Remove(listObject);
I am so sorry i misundersand the question. 我很抱歉我误解了这个问题。
this is my answer,you should use function. 这是我的答案,你应该使用功能。
public xxxx sss(List s,var i)
{
try
{
var result = s.ElementAt(i);
s.Remove(result);
}
catch(Exception e)
{
Console.WriteLine(e.message);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.