Skip to content

Instantly share code, notes, and snippets.

@dgyesbreghs
Created July 16, 2019 19:20
Show Gist options
  • Save dgyesbreghs/dca5eff4a4046c822321157676f0b539 to your computer and use it in GitHub Desktop.
Save dgyesbreghs/dca5eff4a4046c822321157676f0b539 to your computer and use it in GitHub Desktop.
Convert a Object to another Object
namespace Tree
{
class Asset
{
public string Name;
public Asset[] Children = new Asset[0];
public Asset(string name)
{
Name = name;
}
}
}
using System;
using System.Collections.Generic;
namespace Tree
{
class Program
{
static void Main(string[] args)
{
var underlayingNodeOne = new Node("underlayingNodeOne");
var underlayingNodeTwo = new Node("underlayingNodeTwo");
var underlayingNodeThree = new Node("underlayingNodeThree");
Node[] underlayingChildrenOne = new Node[]{ underlayingNodeOne, underlayingNodeTwo };
Node[] underlayingChildrenTwo = new Node[]{ underlayingNodeThree };
var childNodeOne = new Node("childNodeOne");
childNodeOne.Children = underlayingChildrenOne;
var childNodeTwo = new Node("childNodeTwo");
childNodeTwo.Children = underlayingChildrenTwo;
Node[] children = new Node[] { childNodeOne, childNodeTwo };
var node = new Node("Parent");
node.Children = children;
var asset = Convert(node);
Console.WriteLine("Node: " + node.Name);
Console.WriteLine("Node Children: " + node.Children.Length);
Console.WriteLine("Asset: " + asset.Name);
Console.WriteLine("Asset Children: " + asset.Children.Length);
}
static Asset Convert(Node node)
{
var asset = new Asset(node.Name);
asset.Children = Preload(node);
return asset;
}
static Asset[] Preload(Node node)
{
if (node.Children.Length == 0)
{
var asset = new Asset(node.Name);
return new Asset[]{ asset };
}
List<Asset> assets = new List<Asset>();
foreach(var child in node.Children)
{
if (child == null) { continue; }
Console.WriteLine("Name: " + child.Name);
var asset = new Asset(child.Name);
asset.Children = Preload(child);
assets.Add(asset);
}
return assets.ToArray();
}
}
}
namespace Tree
{
class Node
{
public string Name;
public Node[] Children = new Node[0];
public Node(string name)
{
Name = name;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment