Convert tree structure to different types

If I have a class:

class NodeA { public string Name{get;set;} public List<NodeA> Children {get;set;} // etc some other properties } 

and some other class:

 class NodeB { public string Name; public IEnumerable<NodeB> Children; // etc some other fields; } 

If I need to convert a NodeB object to a NodeA type, what would be the best approach? Create a wrapper class? If I need to create a wrapper class, how can I create it so that all wpf controls can still successfully bind to properties?

  • The reason why I need to create such a composition:

    There was an old algorithm that was used in a program that returns a list of characters (IMemorySymbol) in a compiled program. We worked and created a new algorithm, and the fields and properties are slightly different (ISymbolElem). We need to do a temporary selection to display the properties in the wpf application view.

+4
source share
3 answers

The pair is coming ...

Copy constructor

have a NodeA and NodeB node containing a constructor that accepts the opposite:

 class NodeA { public string Name{get;set;} public List<NodeA> Children {get;set;} // COPY CTOR public NodeA(NodeB copy) { this.Name = copy.Name; this.Children = new List<NodeA>(copy.Children.Select(b => new NodeA(b)); //copy other props } } 

Explicit or implicit statement

Explicitly, you will use as NodeA a = (NodeA)b; while implicit you can skip parens.

 public static explicit operator NodeA(NodeB b) { //if copy ctor is defined you can call one from the other, else NodeA a = new NodeA(); a.Name = b.Name; a.Children = new List<NodeA>(); foreach (NodeB child in b.Children) { a.Children.Add((NodeA)child); } } 
+4
source

If you do not need to associate the NodeA implementation with NodeB , add a copy constructor as follows:

 class NodeA { public NodeA() { } public NodeA(NodeB node) { Name = node.Name; Children = node.Children.Select(n => new NodeA(n)).ToList(); } public string Name{get;set;} public List<NodeA> Children {get;set;} // etc some other properties } 

If the connection is troubling, you can create a Convert class that does the conversion for you. Note that the Automapper structure generates these types of transforms for you, using reflection over the source and target types.

+1
source

What about inheritance from a common interface?

 interface INode { public string Name{get;set;} public IEnumerable<INode> Children {get;set;} } class NodeA : INode { public string Name{get;set;} public List<NodeA> Children {get;set;} // etc some other properties } class NodeB : INode { public string Name; public IEnumerable<NodeB> Children; // etc some other fields; } void myMethod() { INode nodeB = new NodeB(); INode nodeA = nodeB; } 
+1
source

All Articles