public class ModelConvertHelper<T> where T:new ()
{
public static IList<T> ConvertToModel(DataTable dt)
{
IList<T> ts = new List<T>();
Type type = typeof(T);
PropertyInfo[] propertys = type.GetProperties();
string tempName;
foreach (DataRow dr in dt.Rows)
{
T t = new T();
foreach (PropertyInfo pi in propertys)
{
tempName = pi.Name;
if(dt.Columns.Contains(tempName))
{
if (!pi.CanWrite) continue;
object value = dr[tempName];
if (value != DBNull.Value) pi.SetValue(t,value,null);
}
}
ts.Add(t);
}
return ts;
}
}
public static DataTable ListToTable(List<T> list)
{
Type type = typeof(T);
PropertyInfo[] proInfos = type.GetProperties();
DataTable dt = new DataTable();
foreach (var p in proInfos)
{
dt.Columns.Add(p.Name, p.PropertyType);
}
foreach (var item in list)
{
DataRow dr = dt.NewRow();
foreach (var p in proInfos)
{
dr[p.Name] = p.GetValue(item);
}
dt.Rows.Add(dr);
}
return dt;
}