Ok this is a little bit hard to ask, but i will try. I have a List with objects (Lots), which contains again a list with objects (Wafers). When i change a value within a wafer it will be changed in both lists! Thats what i want. But when i want to remove a wafer from the copied list, it should not be removed from the orginal list. So i want to have a new List of wafers in each lot but the references to the wafers should be the same as in the original lot because i want to change values to the wafers and it should change the values in the orginal wafer and copied wafer. Is it possible without deep copy?
I have the following code, to explain it better:
public class Lot
{
public string LotName { get; set; }
public List<Wafer> Wafers { get; set; }
}
public class Wafer
{
public string WaferName { get; set; }
}
[Test]
public void ListInListTest()
{
//Some Testdata
List<Lot> lotList = new List<Lot>();
Lot lot = new Lot();
lot.LotName = "Lot1";
lot.Wafers = new List<Wafer>();
Wafer wafer = new Wafer();
wafer.WaferName = "Wafer1";
lot.Wafers.Add(wafer);
wafer = new Wafer();
wafer.WaferName = "Wafer2";
lot.Wafers.Add(wafer);
wafer = new Wafer();
wafer.WaferName = "Wafer3";
lot.Wafers.Add(wafer);
wafer = new Wafer();
wafer.WaferName = "Wafer4";
lot.Wafers.Add(wafer);
lotList.Add(lot);
lot = new Lot();
lot.LotName = "Lot1";
lot.Wafers = new List<Wafer>();
wafer = new Wafer();
wafer.WaferName = "Wafer1";
lot.Wafers.Add(wafer);
wafer = new Wafer();
wafer.WaferName = "Wafer2";
lot.Wafers.Add(wafer);
wafer = new Wafer();
wafer.WaferName = "Wafer3";
lot.Wafers.Add(wafer);
wafer = new Wafer();
wafer.WaferName = "Wafer4";
lot.Wafers.Add(wafer);
lotList.Add(lot);
//Copy the List
List<Lot> copyList = CopyList(lotList);
//That works. It removes the lot just in the copyList but not in
//the original one
copyList.RemoveAt(1);
//This works not like i want. It removes the wafers from the copied list
//and the original list. I just want, that the list will be changed
//in the copied list
copyList[0].Wafers.RemoveAt(0);
}
private List<Lot> CopyList(List<Lot> lotList)
{
List<Lot> result = new List<Lot>(lotList);
foreach (Lot lot in result)
{
lot.Wafers = new List<Wafer>(lot.Wafers);
}
return result;
}
I hope it is not so confusing? And i hope my question is explained good enough.