How to empty a list in C#?

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

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

相关标签:
7条回答
  • 2020-12-09 00:55

    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.

    0 讨论(0)
  • 2020-12-09 01:15

    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
    
    0 讨论(0)
  • 2020-12-09 01:17

    It's really easy:

    myList.Clear();
    
    0 讨论(0)
  • 2020-12-09 01:18

    You can use the clear method

    List<string> test = new List<string>();
    test.Clear();
    
    0 讨论(0)
  • 2020-12-09 01:19

    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.

    0 讨论(0)
  • 2020-12-09 01:19

    you can do that

    var list = new List<string>();
    list.Clear();
    
    0 讨论(0)
提交回复
热议问题