C # clone cross reference list

I have a list of MyItems. MyItem may or may not refer to its peers.

List<MyItem> myList = new List<MyItem>(); myList.add(...) //add all 8 items myList[1].RefTo = myList[3]; myList[5].RefTo = myList[2]; myList[7].RefTo = myList[5]; Item 0 Item 1 ----+ +---> Item 2 | | Item 3 <---+ | Item 4 +--- Item 5 <---+ Item 6 | Item 7 ----+ 

I need to clone the entire list. Each MyItem in the new list is a new copy of MyItems in the old list (without reference), and all links in the new list should point to items in the new list. After that, the new list should work even with the old list, and the old MyItems are completely deleted.

I have an ICloneable interface in MyItem, so the element can be cloned by calling MyItem.Clone (). However, the cloned copy still refers to MyItems in the old list.

How to update MyItems links with objects in a new list? Sample code will be highly appreciated.

+4
source share
1 answer

What you just do is serialize your list into a memory stream and deserialize it and create a clone. Since each object will be serialized only after your RefTo field is saved in the cloned copy as you wish, including circular links

 namespace ConsoleApplication1 { [Serializable] class MyItem { public int MyProperty { get; set; } public MyItem RefTo { get; set; } } class Program { static void Main(string[] args) { List<MyItem> list1 = new List<MyItem>(); list1.Add(new MyItem() { MyProperty = 1 }); list1.Add(new MyItem() { MyProperty = 2 }); list1.Add(new MyItem() { MyProperty = 3 }); list1[1].RefTo = list1[0]; list1[2].RefTo = list1[1]; using (MemoryStream stream = new MemoryStream()) { var bformatter = new BinaryFormatter(); bformatter.Serialize(stream, list1); stream.Seek(0, SeekOrigin.Begin); List<MyItem> clonedCopyList = (List<MyItem>)bformatter.Deserialize(stream); } } } } 
+7
source

Source: https://habr.com/ru/post/1380697/


All Articles