Question

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");       
Was it helpful?

Solution

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 :)

OTHER TIPS

Using the Open source Dynamitey (can be install via nuget, and is a Portable Class Library), you can make expandoobject graphs like this:

  using Dynamitey.DynamicObjects;
  ...

  dynamic New = Builder.New<ExpandoObject>();

  var person = New.Person(
      Name: New.Name(FirstName:"John", SurName:"Smith")
  );

You can also take a bunch of nested IDictionary<string,object> and make them act like a dynamic object with nested dynamic object properties by using:

using Dynamitey.DynamicObjects.Dictionary = DynamicDict;
...

dynamic obj = new DynamicDict(nestedDictionaries);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top