Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preserve lists already created before using List.Clear()

Tags:

c#

asp.net

When I add data to a List, then append that list to another list, then use List.Clear() on the original list, it empties everything and the lists already appended aren't preserved.

Here's an example of what I'm talking about. Lets say I make 2 lists like this:

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

for(int i=0;i<10;i++){

  for(int i2=0;i2<10;i2++){
    list.Add(i2);
  }
  list2.Add(list);
  list.Clear();

}

When I run list.Clear() it clears out all of the pre-existing lists I already appended to list2

I know a work-around would be to re-arrange the code like this:

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

for(int i=0;i<10;i++){

  List<int> list = new List<int>(); //<- moved inside the for

  for(int i2=0;i2<10;i2++){
    list.Add(i2);
  }
  list2.Add(list);

}

But is this normal behavior? Is it possible to preserve the pre-appended lists?

like image 863
Control Freak Avatar asked Sep 18 '14 02:09

Control Freak


People also ask

What does list Clear () function do in Java?

The clear() method of List interface in Java is used to remove all of the elements from the List container. This method does not deleted the List container, instead it justs removes all of the elements from the List.

How do I change my new list without changing the original list in Java?

List<Integer> copy = new ArrayList<>(list); Integer is an immutable class; its value is set when the instance is created, and can never change.


1 Answers

Classes are passed by reference and List<T> is a class. Accordingly, when you clear list it also clears the data passed by reference in list2. See List - do I pass objects or references? for more details.

This should solve the issue shown in your example and create a new copy of list to add to list2 before clearing list:

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

for(int i=0;i<10;i++){

  for(int i2=0;i2<10;i2++){
    list.Add(i2);
  }
  list2.Add(list.ToList()); //modified to create a new List when adding
  list.Clear();

}

See also Jon Skeet's Parameter passing in C# for some broader information on how parameters are passed in C#, especially relating to reference types.

like image 164
jordanhill123 Avatar answered Oct 18 '22 07:10

jordanhill123