Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create a Dynamic tree structure using the ExpandoObject?

at the moment I am using the ExpandoObject to dynamically store firstname and surname.

e.g.

   // Create Expando object for testing
   dynamic employee = new ExpandoObject();

   // Dynamically add the fields to the expando            
   ((IDictionary<String, Object>)employee).Add("FirstName", "John");
   ((IDictionary<String, Object>)employee).Add("Surname", "Smith"); 

I was wondering if it is possible to dynamically store the fields into a tree structure so that i could have the parent field called Name, and then two child fields called Firstname and Surname. Ideally this could potentially be expanded to included more sub levels. I've done some psudo code below to demonstrate ideally how I would like it to work. (of course this code currently causes errors)

// Create Expando object for testing
dynamic employee = new ExpandoObject();

// Dynamically add the Name
((IDictionary<String, Object>)employee).Add("Name", "");

//Dynamically add the firstname and surname to employee.Name
((IDictionary<String, Object>)employee.Name).Add("FirstName", "John");
((IDictionary<String, Object>)employee.Name).Add("Surname", "Smith");       
like image 217
kevchadders Avatar asked May 23 '11 14:05

kevchadders


1 Answers

What stops you from doing

 dynamic parent = new ExpandoObject();
 parent.Nick = "Dad";
 parent.Name = new ExpandoObject();
 parent.Name.FirstName = "John";
 parent.Name.MiddleName = "Tweeds";
 parent.Name.SurName = "Doe";

 parent.Spouse = new ExpandoObject();
 parent.Spouse.Nick = "Sweety";
 parent.Children = new [] {
     new ExpandoObject(),
     new ExpandoObject()
 };
 parent.Children[0].Nick = "P-J";
 parent.Children[0].Name = "Pete-Jay";
 parent.Children[1].Nick = "Tammie";
 parent.Children[1].Name = "Tamara";

Or similar? You wouldn't exactly get tree traversal for free, but that's basically a given when not using strongtypes nodes

Update; I just compiled and ran this using Mono C# compiler on Windows XP. Not even having MS.NET 4.0 installed :)

like image 138
sehe Avatar answered Sep 19 '22 01:09

sehe