krisna
krisna

Reputation: 11

Ways clear the list in c#

I have a simple list

//here I have declared a static list

public static List list1 = new List();

here I can clear the list by using list.clear() method, Is there any other methods to clear the list.

Upvotes: 0

Views: 516

Answers (4)

Gildor
Gildor

Reputation: 2574

According to your comment you are trying to clear several lists. Where are the lists stored?

If they are stored in a collection named lists, you can clear all of them with:

foreach(var list in lists)
{
    list.Clear();
}

Upvotes: 1

Sai Avinash
Sai Avinash

Reputation: 4753

I can see no reason why you are not using list.clear();

It is the best way to do it.

Alternative, if you need,

is by removing each and every list element

int iCount=listToBeRemoved.items.count;

    foreach (int i=0;i<iCount;i++)
            {
                listToBeRemoved.Remove(i);
            }

Hope this helps..

Note: I strongly recommend you to use list.Clear()

Upvotes: 0

Muhammad Essa
Muhammad Essa

Reputation: 142

you can use like this

list=null;

then all the list will be considered as empty or clear... hope this help you.

Upvotes: 0

Sajad Karuthedath
Sajad Karuthedath

Reputation: 15767

You can assign the List to null instead of calling Clear, with similar performance.

But: After assigning to null, you must call the constructor again to avoid getting a NullReferenceException.

Upvotes: 0

Related Questions