I have a list that gets filled in with some data from an operation and I am storing it in the memory cache. Now I want another list which contains some sub data from the list based on some condition.
As can be seen in the below code I am doing some operation on the target list. The problem is that whatever changes I am doing to the target list is also being done to the mainList. I think its because of the reference is same or something.
All I need is that operation on the target list not affect data inside the main list.
List<Item> target = mainList;
SomeOperationFunction(target);
void List<Item> SomeOperationFunction(List<Item> target)
{
target.removeat(3);
return target;
}
Python List Copy() function does not change the original list is unchanged when the new list is modified. It is called a shallow copy.
You need to clone your list in your method, because List<T>
is a class, so it's reference-type and is passed by reference.
For example:
List<Item> SomeOperationFunction(List<Item> target)
{
List<Item> tmp = target.ToList();
tmp.RemoveAt(3);
return tmp;
}
Or
List<Item> SomeOperationFunction(List<Item> target)
{
List<Item> tmp = new List<Item>(target);
tmp.RemoveAt(3);
return tmp;
}
or
List<Item> SomeOperationFunction(List<Item> target)
{
List<Item> tmp = new List<Item>();
tmp.AddRange(target);
tmp.RemoveAt(3);
return tmp;
}
You need to make a copy of the list so that changes to the copy won't affect the original. The easiest way to do that is to use the ToList
extension method in System.Linq
.
var newList = SomeOperationFunction(target.ToList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With