Candy Crush
Candy Crush

Reputation: 11

How do I clear the value of a nested List<T>?

For example, how do I clear the value of list? List.Clear does not work

List<List<int>> list = new List<List<int>>();

Upvotes: 1

Views: 1414

Answers (3)

Pierre-Luc Pineault
Pierre-Luc Pineault

Reputation: 9191

You need to clear the values manually in each inner lists. You can do that with any loop, here's an example with foreach and for :

foreach(List<int> innerItem in list)
{
    innerItem.Clear();
}



for(int i = 0; i < list.Count; i++)
{
    list[i].Clear();
}

By doing onlylist.Clear() you delete every item and every inner list.

Upvotes: 1

Jonesopolis
Jonesopolis

Reputation: 25370

list.ForEach(l => l.Clear());

using list.Clear() will clear your outer list. The above code will clear your inner lists, leaving you with a list of empty lists

Upvotes: 0

gleng
gleng

Reputation: 6304

Just do a foreach statement to access each individual list. Then call clear on it.

foreach (var item in list)
    item.Clear()

Upvotes: 4

Related Questions