How to empty a list in C#?

前端 未结 7 1033
旧时难觅i
旧时难觅i 2020-12-09 00:24

I want to empty a list. How to do that?

相关标签:
7条回答
  • 2020-12-09 01:20

    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);
    
    0 讨论(0)
提交回复
热议问题