【发布时间】:2020-06-07 03:57:12
【问题描述】:
我正在尝试将列表转换为数据表。我已经完成了基本大纲,但被困在一个部分。我试图只从类中获取一些属性。
public static DataTable ToDataTable<T>(this IList<T> data)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
table.Columns.Add("type", typeof(string));
table.Columns.Add("id", typeof(Int32));
table.Columns.Add("name", typeof(string));
table.Columns.Add("city", typeof(string));
foreach (T item in data)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
{
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
}
table.Rows.Add(row);
}
return table;
}
问题是当它到达第二个属性时,它会抛出一个错误,指出列 'unincludedCol' 不属于表。
我该如何解决这个问题?
【问题讨论】:
-
在您的内部
foreach中添加一个if语句,仅当属性名称在{"type", "id", "name", "city"}中时才起作用
标签: c#