实体类转datatable 遇到就个坑 习惯了如下定义类:
public class DocType
{
public string Code ;
public string Name ;
}
结果 GetProperties 获取不到 字段及属性名 记录一下
public class DocType
{
public string Code { get; set; }
public string Name { get; set; }
public DocType()
{}
public DocType(string code, string name)
{
Code = code;
Name = name;
}
}
public static DataTable ToDataTable(this List items)
{
DataTable dataTable = new DataTable();
IList PropList = new List(typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance));
foreach (PropertyInfo prop in PropList )
{
dataTable.Columns.Add(prop.Name);
}
foreach (T obj in items)
{
var values = new object[PropList .Count];
for (int i = 0; i < PropList .Count; i++)
{
values[i] = PropList [i].GetValue(obj, null);
}
dataTable.Rows.Add(values);
}
return dataTable;
}