简体   繁体   中英

How to add a propery to a dynamic object knowing the name of the column only at runtime

This article shows how to add properties to a dynamic object.

dynamic contact = new ExpandoObject();
contact.Name = “Patrick Hines”;
contact.Phone = “206-555-0144”;

What if I've instead an array of columns ["Id", "Name", "Phone"] .

DataTable dt = ContactRepository.GetContactInfo(sqlText, columns);

When I get the result, I'd like to do something like

foreach(DataRow row in dt.Rows)
{
   dynamic contact = new ExpandoObject();

   foreach(string colName in columns)
   {
      // extract the value of the column from the row
      // add an property that has the same name has the column name
   }
}

I'm trying to avoid to have to check for each possible columns before adding it.

There are at least 36 columns.

if(columns.Contains("Phone"))
   contact.Phone = row["Phone"].ToString();

This last feature that I'd really like to implement to avoid all those checks.

Thank you for helping

So, I don't know how to work with DataRow class, but I know how to work with Expando in this case:

foreach(DataRow row in dt.Rows)
{
    IDictionary<string,object> contact = new ExpandoObject();
    foreach(string colName in columns)
    {
        contact.Add(colName,row[colName]);
    }
    dynamic contactDynamic = contact as ExpandoObject;
    Console.WriteLine(contact.Phone);
}

Be care! ExpandoObject implements IDictionary interface, not Dictionary class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM