How to create a dynamic property in this scenario [duplicate]
I have a list which contains dynamic data. i.e
list[0].id=0;
list[1].id=1;
list[2].id=2;
I want to create a class which will have dynamic property names i.e
for(int i=0;i<list.count;i++)
{
//create dynamic class with dynamic property name
new {id+i=list[i].id} //this statement throws compilation error.
}
what is alternative to this method?
You can't do what you are after with Anonymous classes as they build at compile time and not runtime. You need to use the ExpandoObject class
dynamic expando = new ExpandoObject();
var p = expando as IDictionary<String, object>;
for(int i=0;i<list.count;i++)
{
p[id+i] = list[i].id;
}
//do something with the expando object
This is based on the post that Jani linked in his comment.
精彩评论