Problem with edit list <double []> in C #
I pass a list of type double [] to a function in the class, editing the values ββinside the function using tempList, and then return the edited values. But the transferred source list is also being edited, and I do not want them to be edited according to tempList.
Here is the code.
List<double[]> newList = new List<double[](); newList = myClass.myFunction(value, originalList); // myClass ... // myFunction public List<double[]> myFunction(int value, List<double[]> myList) { List<double[]> tempList = new List<double[]>(); for (int i = 0; i < myList).Count; i++) { tempList.Add(myList[i]); } // Do stuff to edit tempList return tempList; }
Keep in mind that arrays are reference types. When you add an array to tempList
, only the array reference is added, so myList
and tempList
both refer to the same double[]
objects.
Instead, you need to make a clone of arrays:
for (int i = 0; i < myList.Count; i++) { tempList.Add((double[])myList[i].Clone()); }
The problem you are facing: double[]
is the type of link, not the type of value, so when you add it to your tempList
, you add a link to the original object, not to the new object. In fact, you need to create a new double[]
before adding it to tempList
so that you don't work on the original object.
Assuming you can use LINQ, you don't need to go in cycles. You can do something like:
var tempList = myList.Select(x => x.ToArray()).ToList();
This is because Collections / reference types are passed by reference. (In fact, the holding variable is passed by value, but all variables point to the same link).
Detailed explanation read this SO answer
If you want the changes in my function not to be reflected in the original collection, you should copy / clone it and then go to myFunction
.
Example
newList = myClass.myFunction(value, (List<double>)originalList.Clone());
tempList.Add(myList[i]);
means that you add a reference to the double [] object on the index i in the list of topics. therefore, if you edit the value of this object, you will get a chance for both lists.
if you want to have different cloned lists that will not affect each other, you will need to do this:
List<double[]> tempList = new List<double[]>(); for (int i = 0; i < myList).Count; i++) { double[] originalListItem = myList[i]; // the most important step here!!! - clone the originalListItem to clonedListItem tempList.Add(clonedListItem); } // Do stuff to edit tempList return tempList;
You are inserting array references in tempList, not a copy of the array. Therefore, if you change the value in tempList, you change the original array.
This code will work better:
for (int i = 0; i < myList.Count; i++) { var copy = new Double[myList[i].Length]; Array.Copy(myList[i], copy, myList[i].Length); tempList.Add(copy); }