Creating a list of ExpandoObjects with properties read from an array
Asked Answered
B

1

12

I'm trying to create a dynamic list of objects because I don't know what properties my objects will have until I read them from a file.

So suppose I have the properties of my object inside an array (e.g. FirstName, LastName,Email).

I want to create dynamic objects called Recipient with the above properties. Then I want to create a list and add some of these objects to that list.

I have done the following so far but I'm not sure if this is correct way of assigning properties to a dynamic object ("fields" is the name of the array):

var persons = new List<dynamic>();
dynamic Recipient = new ExpandoObject() as IDictionary<string, Object>;
foreach (string property in fields)
{
   Recipient.property = string.Empty;
}

How do I create a recipient object with the properties mentioned above and then add those recipients to the persons list?

Balfore answered 7/1, 2013 at 15:36 Comment(0)
P
15

ExpandoObject implements the IDictionary<string, object> interface, where the key/values would be mapped to the the member name/values. If you have the property names in the fields array, you'd just use those as the dictionary keys:

IDictionary<string, object> recipient = new ExpandoObject();
foreach (string property in fields)
{
   recipient[property] = string.Empty;
}
Peirce answered 7/1, 2013 at 15:54 Comment(4)
so far so good. now please tell me how do I print recipient's properties in the console once these properties are assigned.Balfore
that means looping through recipient's properties in order to get e.g. FirstName, LastName,Email on the screen because I need these properties to create my objects with.Balfore
@Pedram since you only know the property names at runtime, yes, you need to enumerate it as a dictionary to get the name/values.Saari
foreach(var kv in (IDictionary<string, object>)recipient) Console.WriteLine("Key:{0} Value:{1}", kv.Key, kv.Value);Saari

© 2022 - 2024 — McMap. All rights reserved.