Øyv*_*hen 209
这真的很容易:
myList.Clear();
Run Code Online (Sandbox Code Playgroud)
ang*_*son 27
如果用"list"表示a List<T>
,那么Clear方法就是你想要的:
List<string> list = ...;
...
list.Clear();
Run Code Online (Sandbox Code Playgroud)
你应该养成在这些东西上搜索MSDN文档的习惯.
以下是如何快速搜索该类型的各种位的文档:
List<T>
类本身(这是你应该开始的地方)所有这些Google查询都列出了一系列链接,但通常您需要谷歌在每种情况下提供的第一个链接.
给出一个替代答案(谁需要5个相同的答案?):
list.Add(5);
// list contains at least one element now
list = new List<int>();
// list in "list" is empty now
Run Code Online (Sandbox Code Playgroud)
请记住,旧列表的所有其他引用尚未清除(根据具体情况,这可能是您想要的).此外,在性能方面,它通常有点慢.
选项#1:使用Clear()函数清空List<T>
并保留其容量.
Count设置为0,并且还会释放对集合元素中其他对象的引用.
容量保持不变.
选项#2 - 使用Clear()和TrimExcess()函数设置List<T>
为初始状态.
Count设置为0,并且还会释放对集合元素中其他对象的引用.
修剪为空
List<T>
将List的容量设置为默认容量.
定义
Count =实际中的元素数List<T>
容量 =内部数据结构在不调整大小的情况下可以容纳的元素总数.
仅清除()
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);
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)
您可以使用clear方法
List<string> test = new List<string>();
test.Clear();
Run Code Online (Sandbox Code Playgroud)