Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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;
}
like image 757
user505210 Avatar asked Dec 20 '12 17:12

user505210


People also ask

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

Python List Copy() function does not change the original list is unchanged when the new list is modified. It is called a shallow copy.


2 Answers

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;
}
like image 71
Leri Avatar answered Sep 21 '22 06:09

Leri


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());
like image 32
Servy Avatar answered Sep 21 '22 06:09

Servy