0

Let's say that I have a a list of elements of 'n' size. I want to add 'n' properties in a dynamic object .How can I achieve this? We can't just hard code it because length of list is dynamic.

So an object is required in which I need to add properties on the basis of length of list.

object should contain all element of list as seperate field .We can't store it in a data structure

dynamicobj = new ExpandoObject();
foreach(Employee emp in EMPLIST){
    temp=emp.FirstName;    //emp is object of Employee class and Emplist contains object of employee class
    obj.temp=emp;
}
dbc
  • 104,963
  • 20
  • 228
  • 340
  • Looks like the `ExpandoObject` is what you are looking for and you have already found it. Can you please explain why it is not suitable for your needs? – Serg Jul 06 '23 at 15:16
  • `ExpandoObject` implements `IDictionary` explicitly so cast it to that interface and add using the `Add(string, object)` method. I.e. `((IDictionary)dynamicobj).Add(emp.FirstName, emp);`. See [this answer](https://stackoverflow.com/a/4938442) by Stephen Cleary to [Dynamically adding properties to an ExpandoObject](https://stackoverflow.com/q/4938397). – dbc Jul 06 '23 at 15:42
  • Do note that if two employees have a duplicated first name you will get an `ArgumentException`, so consider whether this is really the best data model to use. – dbc Jul 06 '23 at 15:44

0 Answers0