如何在C#中清空列表?


109

我想清空列表。怎么做?


34
响应时间比读取/搜索MSDN
V4Vendetta 2011年

27
另外,现在比MSDN更容易在这里找到答案。
马特·康诺利

14
更不用说一个事实,如果您是Google .net empty list,那么此页面将 MSDN 之前出现
维维安河

2
@ V4Vendetta在2018年,我建议StackOverflow应该创建一个Bot,该Bot会将您的评论放在评论中具有指向MSDN doc链接的任何线程上……
scharette

Answers:


234

真的很简单:

myList.Clear();

3
......如果列表实际上是一个List<>ArrayList或器具IList。;)
Lucero

3
@Lucero两者都不是吗?
斯里尼瓦斯·雷迪·塔蒂帕西

16
由于这是Google的热门话题,因此我遇到了这个问题,因此我对此发表了评论。如果在循环中使用相同的列表并使用clear,则该列表通常会保留对旧对象的引用-我经常最终使用= new LisT <T>();。由于它会立即清除所有旧分配。对于大多数人来说,.Clear(); 就足够了,但是如果您发现一个列表的行为异常-请尝试使用= new List <T>();。
2014年

1
我将对此进行双重谴责,因为从2020年开始,这里已经提供了一些错误信息。List<T>.Clear正确清除所有引用,这使GC可以在必要时清除分配。new List<T>不能做到这一点,并且不适用于所有情况
约翰·

28

如果通过“列表”表示a List<T>,那么Clear方法就是您想要的:

List<string> list = ...;
...
list.Clear();

您应该养成在这些方面搜索MSDN文档的习惯。

以下是快速搜索有关该类型各个位的文档的方法:

所有这些Google查询都列出了一系列链接,但通常情况下,您都希望google提供给您的第一个链接。


“所有这些都列出了一堆链接,但是通常您想要第一个。” 除非您想清空列表?
CVn

抱歉,我应该更清楚了。通常,您需要Google提供的第一个链接,而不是“列表类别”。
Lasse V. Karlsen

9

给出替代答案(谁需要5个相等的答案?):

list.Add(5); 
// list contains at least one element now
list = new List<int>();
// list in "list" is empty now

请记住,对旧列表的所有其他引用都尚未清除(取决于情况,这可能是您想要的)。同样,在性能方面,它通常会慢一些。


您是否可以验证设置list = new List <>()实际上比list.Clear();慢?根据MSDN(下面的链接)list.Clear();。是O(N)操作,我无法想象实例化一个新列表会花费更长的时间。 msdn.microsoft.com/zh-CN/library/dwb5h52a(v=vs.110).aspx
Chris Tramel 2015年

5
DotNetPerls做了一个基准测试,发现新的List <>更快。dotnetperls.com/list-clear
Gerhard Powell,

顺便说list一句,也请牢记有新参考。因此,如果要在该列表上使用锁,请不要使用它。
jeromej

9

选项1:使用Clear()函数清空List<T>并保留其容量。

  • Count设置为0,并且也会释放对集合元素中其他对象的引用。

  • 容量保持不变。

选项2-使用Clear()TrimExcess()函数设置List<T>为初始状态。

  • Count设置为0,并且也会释放对集合元素中其他对象的引用。

  • 修剪为空会将List<T>列表的容量设置为默认容量。

定义

Count =实际存在于元素中的元素数List<T>

容量 =内部数据结构无需调整大小即可容纳的元素总数。

仅Clear()

List<string> dinosaurs = new List<string>();    
dinosaurs.Add("Compsognathus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Deinonychus");
Console.WriteLine("Count: {0}", dinosaurs.Count);
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);
dinosaurs.Clear();
Console.WriteLine("\nClear()");
Console.WriteLine("\nCount: {0}", dinosaurs.Count);
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);

Clear()和TrimExcess()

List<string> dinosaurs = new List<string>();
dinosaurs.Add("Triceratops");
dinosaurs.Add("Stegosaurus");
Console.WriteLine("Count: {0}", dinosaurs.Count);
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);
dinosaurs.Clear();
dinosaurs.TrimExcess();
Console.WriteLine("\nClear() and TrimExcess()");
Console.WriteLine("\nCount: {0}", dinosaurs.Count);
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);


5

您可以使用清除方法

List<string> test = new List<string>();
test.Clear();

4

像这样,您需要列表上的Clear()函数。

List<object> myList = new List<object>();

myList.Add(new object()); // Add something to the list

myList.Clear() // Our list is now empty
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.