Reputation: 13
I have following code:
List<T> firstList; //list with some items
List<T> secondList = firstList //copyOfFirstList
List<T> elementsToDelete = secondList.FindAll(whichShouldIDelete);
foreach(var item in elementsToDelete){
secondList.Remove(item);
}
The problem is that Remove() method does not delete items only from secondList. Items are deleted from both firstList and secondList. So when I remove 20 items from secondList, the same elements are removed from firstList. What may be the cause of this situation?
Upvotes: 1
Views: 2012
Reputation: 41
public static List<T> CloneList<T>(List<T> oldList)
{
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
formatter.Serialize(stream, oldList);
stream.Position = 0;
return (List<T>)formatter.Deserialize(stream);
}
private void button1_Click(object sender, EventArgs e)
{
List<string> firstList = new List<string>() { "1", "2", "3"}; //list with some items
List<string> secondList = CloneList(firstList); //copyOfFirstList
List<string> elementsToDelete = new List<string>() { "1" }; // do some logic to find all items you need to delete
foreach (var item in elementsToDelete)
{
secondList.Remove(item);
}
}
Upvotes: 0
Reputation: 1550
It is because both lists point to the same "address", so editing one affects the other.
try
List<T> firstList = new List<T>();
List<T> secondList = new List<T>();
secondList.AddRange(firstList);
Upvotes: 0
Reputation: 26856
As List<T>
is reference type, not value one, then List<T> secondList = firstList;
is not a copy, but just a reference to the same object.
Upvotes: 0
Reputation: 1845
Your assumption:
List<T> secondList = firstList //copyOfFirstList
is only partially right. Is it a shallow reference copy.
The secondList refers to the same object in a different variable.
Google for DeepCopy List to find answers that may match your expectation
Upvotes: 0
Reputation: 223257
The problem is with this line:
List<T> secondList = firstList //copyOfFirstList
It is not creating a copy of the list, instead there are now two references pointing to the same instance of list.
You can do:
List<T> secondList = firstList.ToList(); // explicitly creating a new list.
or
List<T> secondList = new List<T>(firstList);
But remember, if your List<T>
has a reference type (class) then the object of each list would point to the same instance. (A shallow copy of object will be available). So if you do:
firstList[0].SomeProperty = 2;
and if that item exists in secondList
then you will see the property change in second list as well.
Upvotes: 6