How to empty a list in C#?
I want to empty a list. How to do that?开发者_如何学Python
It's really easy:
myList.Clear();
If by "list" you mean a List<T>
, then the Clear method is what you want:
List<string> list = ...;
...
list.Clear();
You should get into the habit of searching the MSDN documentation on these things.
Here's how to quickly search for documentation on various bits of that type:
- List Class - provides the
List<T>
class itself (this is where you should've started) - List.Clear Method - provides documentation on the method Clear
- List.Count Property - provides documentation on the property Count
All of these Google queries lists a bundle of links, but typically you want the first one that google gives you in each case.
Option #1: Use Clear() function to empty the List<T>
and retain it's capacity.
Count is set to 0, and references to other objects from elements of the collection are also released.
Capacity remains unchanged.
Option #2 - Use Clear() and TrimExcess() functions to set List<T>
to initial state.
Count is set to 0, and references to other objects from elements of the collection are also released.
Trimming an empty
List<T>
sets the capacity of the List to the default capacity.
Definitions
Count = number of elements that are actually in the List<T>
Capacity = total number of elements the internal data structure can hold without resizing.
Clear() Only
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() and 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);
To give an alternative answer (Who needs 5 equal answers?):
list.Add(5);
// list contains at least one element now
list = new List<int>();
// list in "list" is empty now
Keep in mind that all other references to the old list have not been cleared (depending on the situation, this might be what you want). Also, in terms of performance, it is usually a bit slower.
you can do that
var list = new List<string>();
list.Clear();
You can use the clear method
List<string> test = new List<string>();
test.Clear();
You need the Clear() function on the list, like so.
List<object> myList = new List<object>();
myList.Add(new object()); // Add something to the list
myList.Clear() // Our list is now empty
精彩评论