简体   繁体   English

如何从List中删除对象 <T> 在C#中返回被删除的对象?

[英]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.

相关问题 如何从C#中的列表中删除对象 - how to remove an object from a list in C# 从列表中删除C#对象会丢失引用 - c# object loses reference when removed from list C#从对象列表中删除对象 - C# Remove object from list of objects 从对象列表中删除重复项 c# - Remove Duplicates from Object List c# 退货清单 <object> 来自IEnumerable C# - Return List<object> from IEnumerable C# 如何从另一个类的列表中删除对象? C# - How to remove an object from a list in another class? c# C#如何从列表中返回1行<T>作为参数传递的对象 - C# how to return 1 row from List<T> object passed as parameter 如何从c#中的web api返回动态对象列表 - How to return a dynamic object list from web api in c# 如何从列表转换<object>列出<t>在 c# 中?<div id="text_translate"><p> 我有一个 Class:</p><pre> public class Element { public List&lt;object&gt; objects { get; set; } }</pre><p> 还有一个 Class:</p><pre> public class Node { public long id { get; set; } }</pre><p> 我传入一个List&lt;object&gt; nodes 。 那么有什么方法可以将这些List&lt;object&gt; objects转换为List&lt;Node&gt; nodes ?</p><p> 我试过这种方式,但它不起作用List&lt;Node&gt; nodes = objects.Select(s =&gt; (nodes)s).ToList();</p></div></t></object> - How to convert from List<object> to List<T> in c#? 如何使用列表C#返回对象 - How to return object using list c#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM