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

心已入冬 提交于 2019-12-11 10:36:43

问题


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.


回答1:


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...



来源:https://stackoverflow.com/questions/29191600/how-to-add-dynamic-member-name-and-value-to-an-instance-of-expandoobject-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!