写代码的时候有些控件是直接DataTable,有的是直接绑定Model的,需要两者之间进行互转换
1.DataTable转为实体
#region dataTable 转为实体
public static List<T> TableToList<T>(DataTable dt) where T : class, new()
{
Type type = typeof(T);
List<T> list = new List<T>();
foreach (DataRow row in dt.Rows)
{
PropertyInfo[] properties = type.GetProperties();
T model = new T();
foreach (PropertyInfo p in properties)
{
object value = row[p.Name];
if (value == DBNull.Value)
{
p.SetValue(model, "", null);
}
else
{
if (value is decimal)
{
p.SetValue(model, Convert.ToInt32(value), null);
}
else
{
p.SetValue(model, value, null);
}
}
}
list.Add(model);
}
return list;
}
#endregion
2.实体转为DataTable
public static DataTable ListToDataTable<T>(List<T> items)
{
var tb = new DataTable(typeof(T).Name);
PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in props)
{
Type t = GetCoreType(prop.PropertyType);
tb.Columns.Add(prop.Name, t);
}
foreach (T item in items)
{
var values = new object[props.Length];
for (int i = 0; i < props.Length; i++)
{
values[i] = props[i].GetValue(item, null);
}
tb.Rows.Add(values);
}
return tb;
}