The exact instantiation is
List
- > xList = new List
- >();
Now, if I want to create a shallow copy of this Generic List, I would have to use the GetRange method...I've tried this....I've done a lot of different things to achieve this shallow copy, but what ends up happening is any edits I make to the shallow copy are reflected in the original List as well.
here's an example of what I'm talking about:
int[] x = new int[5] { 3, 5, 7, 9, 11 };
List
tList.Add(x);
List
yList[0][0] = 12;
In this case, xList[0][0] Also gets changed to the value of 12. Can anyone help me with this short of looping through the entire data list????
AlanPosted May 6, 2008, 11:27 AM
I didn't follow your first example as yList is a list of int arrays and you can't therefore set the first element to 12.
However, when I did this, the results were the same as I'd have expected because the same int[] object is being referenced:
List
> xList = new List
>(); iList = new List(); yList = new List(xList[0]);
List
int[] x = new int[5] { 3, 5, 7, 9, 11 };
iList.Add(x);
xList.Add(iList);
List
yList[0][0] = 12;
Console.WriteLine(yList[0][0]); // 12
Console.WriteLine(xList[0][0][0]); // 12
Sherwin HamidiPosted May 6, 2008, 10:06 AM
List
> xList = new List(); yList = new List(xList[0]);
//Populate xList with data here
List
yList[0] = 12;
Console.WriteLine(yList[0].ToString());
Console.WriteLine(xList[0][0].ToString());
results in different values.
The issue does exist, however, when I try to do:
List
>> xList = new List
>>();
//Populate xList
List
> yList = new List
>(xList[0]);
yList[0][0] = 12;
Console.WriteLine(yList[0][0].ToString());
Console.WriteLine(xList[0][0][0].ToString());
AlanPosted May 5, 2008, 4:51 PM
Sherwin HamidiPosted May 5, 2008, 4:43 PM
Sherwin HamidiPosted May 5, 2008, 4:43 PM
Any way around this?
AlanPosted May 5, 2008, 4:34 PM
As the List contains int[], which is a reference type, creating a shallow copy of the List just copies the references, not the array elements.
You therefore need to create shallow copies of the int[]'s themselves:
int[] x = new int[5] { 3, 5, 7, 9, 11 };
List tList = new List(); yList = new List();
tList.Add(x);
List
foreach(int[] ia in tList)
{
yList.Add((int[])ia.Clone());
}
yList[0][0] = 12;
Console.WriteLine(yList[0][0]); // 12
Console.WriteLine(tList[0][0]); // 3