Search code examples
c#c#-4.0expandoobject

How to add dynamic member name and value to an instance of ExpandoObject class?


Let’s say list of member names stored in an array like below,

string[] myMembers = { "ChapterName", "Medium", "LastName", "OrderID" };

I wrote the following code to generate dynamic class and members along with random values.

var myDynamicClassList = new List<ExpandoObject>();
        foreach (var MemberName in myMembers)
        {
            dynamic dynamicClass = new ExpandoObject();
            dynamicClass.MemberName = new Random().Next();
            myDynamicClassList.Add(dynamicClass);
        }

In order to display output of the above myDynamicClassList I wrote the following code.

foreach (var x in myDynamicClassList)
        {
            foreach (var property in (IDictionary<String, Object>)x)
            {
                Console.WriteLine(property.Key + ": " + property.Value);
            }
        }

Showing output like this

MemberName : 123465461

MemberName : 564613611

MemberName : 134654321

MemberName : 786451214

But Instead of above output I am expecting the output like below

ChapterName : 123465461

Medium : 564613611

LastName : 134654321

OrderID : 786451214

Here is my question, is it possible to add dynamic member name to a dynamic class in c#. If it is possible please let me know, if not please guide me to complete this job.

I really appreciate your help in advanced.


Solution

  • As described in a similar question ("Dynamically adding properties to an ExpandoObject"), you can do this by using IDictionary directly:

    string[] myMembers = { "ChapterName", "Medium", "LastName", "OrderID" };
    var myDynamicClassList = new List<ExpandoObject>();
    Random random = new Random();
    foreach (var MemberName in myMembers)
    {
        IDictionary<string, object> dynamicClass = (IDictionary<string, object>)(new ExpandoObject());
        dynamicClass.Add(MemberName, random.Next());
        myDynamicClassList.Add((ExpandoObject)dynamicClass);
    }
    foreach (var x in myDynamicClassList)
    {
        foreach (var property in (IDictionary<String, Object>)x)
        {
            Console.WriteLine(property.Key + ": " + property.Value);
        }
    }
    

    However, you should be aware of possible known memory limitations with this method as described in the comments of the post linked above, or in the Microsoft issue. I would possibly rethink the design to consider what properties are actually needed, or simply using a Dictionary if it's feasible (to avoid the dynamic ExpandoObject entirely).

    I also moved your Random outside of the loop. Creating new instances of Random inside a loop may not give you the results you expect...