Home > Software design >  How can I add a ExpandoObject to an already existing ExpandoObject?
How can I add a ExpandoObject to an already existing ExpandoObject?

Time:03-31

Here is my code:

dynamic App = new ExpandoObject();
//App names are SAP, CRM and ERP 

//App names - adding static
//App.SAP = new ExpandoObject();
//App.CRM = new ExpandoObject();
//App.ERP = new ExpandoObject();

In the last 4 lines, I am adding an ExpandoObject static as I know the app names previously. But I want to do this dynamically.

I can do for the properties dynamically:

AddProperty(App.SAP, "Name", "sap name");
AddProperty(App.SAP, "UserID", "sap userid");
AddProperty(App.SAP, "EmailID", "[email protected]");
AddProperty(App.SAP, "GroupOf", "group1, group2, group3");


public static void AddProperty(ExpandoObject expando, string propertyName, object propertyValue)
{
    // ExpandoObject supports IDictionary so we can extend it like this
    var expandoDict = expando as IDictionary<string, object>;
    if (expandoDict.ContainsKey(propertyName))
        expandoDict[propertyName] = propertyValue;
    else
        expandoDict.Add(propertyName, propertyValue);
}

But I need to add this object App.SAP to this App which is also an ExpandoObject, so I can add App.CRM or App.ERP dynamically later on.

CodePudding user response:

You will get

ExpandoObject doesn't have a definition for SAP...

with this approach:

AddProperty(App.SAP, "Name", "sap name");

as you didn't declare the SAP in APP ExpandoObject.


Instead, you can try to modify the AddProperty method by providing the parentName and deal with the nested object.

AddProperty(App, "SAP", "Name", "sap name");
AddProperty(App, "SAP", "UserID", "sap userid");
AddProperty(App, "SAP", "EmailID", "[email protected]");
AddProperty(App, "SAP", "GroupOf", "group1, group2, group3");
public static void AddProperty(ExpandoObject expando, string parentName, string propertyName, object propertyValue)
{
    // ExpandoObject supports IDictionary so we can extend it like this
    var expandoDict = expando as IDictionary<string, object>;
    if (expandoDict.ContainsKey(parentName))
    {
        ((IDictionary<string, object>)expandoDict[parentName])[propertyName] = propertyValue;
    }
    else
    {
        Dictionary<string, object> child = new Dictionary<string, object>
        {
            { propertyName,  propertyValue }
        };
            
        expandoDict.Add(parentName, child);
    }
}

Sample program

  • Related