[英]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"]
. 如果我改用
["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. 至少有36列。
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: 因此,我不知道如何使用
DataRow
类,但是在这种情况下,我知道如何使用Expando
:
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. ExpandoObject
实现IDictionary
接口,而不是Dictionary
类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.