1

I have the below class for generating Hierarchy Tree structure

public class DynaTreeNode
{
    #region---Property---
    public string title { get; set; }     
    public string key { get; set; }
    public object icon { get; set; }
    List<DynaTreeNode> _children = new List<DynaTreeNode>();
    public List<DynaTreeNode> children
    {
        get { return _children; }
        set { _children = value; }
    }      
}

Also i have a list of DynaTreeNode

List<DynaTreeNode> wholeTree = new List<DynaTreeNode>();//originally from DB

Now i want to clone this List collection into a new List

Todo this I am thinking to use

wholeTree.Select(i => i.Clone()).ToList();

In this case i need to implement IClonable Interface to DynaTreeNode. But the problem is IClonable will not do a deep copy. From http://blogs.msdn.com/b/brada/archive/2003/04/09/49935.aspx

Referred How do I clone a generic list in C#?

This answer also use IClonable.

How can I clone my List with deep copy?.

Note: I want all the children (List) also should get cloned.

Community
  • 1
  • 1
Murali Murugesan
  • 22,423
  • 17
  • 73
  • 120

2 Answers2

3

If performance is not too much of an issue, you can use serialization to implement an general deep cloning approach (e.g., see this question, this question, this question, or have a look at this article).

If this is not an option (e.g., due to performance concerns), you'll have to implement a dedicated method to clone your nodes. For instance, your approach

wholeTree.Select(i => i.Clone()).ToList();

is perfectly valid. Your own implementation of the Clone method may of course return a deep clone (ICloneable does not specify whether deep or shallow; this is the reason why many people consider ICloneable harmful)

Community
  • 1
  • 1
bigge
  • 1,488
  • 15
  • 27
  • I already mentioned that i read this post http://stackoverflow.com/questions/222598/how-do-i-clone-a-generic-list-in-c . This itself have the answer with a static method DeepClone and use Serialization. But would like to know is there any other way other than serialization :) – Murali Murugesan Feb 22 '13 at 06:48
1

My answer is simple (sorry, i have bad english for hard-answer :))

You may use recursion for select subelements.

You need write function which will be call self and return subelements

user2071747
  • 201
  • 1
  • 3
  • 8
  • Here's an answer for Cloning Method using Recursion and Reflection: https://stackoverflow.com/a/52097307/4707576 – BenSabry Aug 31 '18 at 11:05