public List<T> DataTableToModelList<T>(DataTable table)
{
List<T> list = new List<T>();
T t = default(T);
PropertyInfo[] propertypes = null;
string tempName = string.Empty;
foreach (DataRow row in table.Rows)
{
t = Activator.CreateInstance<T>();
propertypes = t.GetType().GetProperties();
foreach (PropertyInfo pro in propertypes)
{
tempName = pro.Name;
if (table.Columns.Contains(tempName))
{
object value = row[tempName].ToString();
if (value.GetType() == typeof(System.DBNull))
{
value = null;
}
pro.SetValue(t, value, null);
}
}
list.Add(t);
}
return list;
}
下边展示实际中的用法
public void GetData()
{
using (MySqlHelper helper = new MySqlHelper(conn))
{
List<Data> info= new List<Data>();
DataSet ds = helper.ExecuteDataSet("select * from Data", CommandType.Text);
info= DataTableToModelList<Data>(ds.Tables[0]);
}
}
public class Data
{
public string Name { get; set; }
public int Id{ get; set; }
}
这样就实现了把Datatable转换为指定ModelList的过程,注意Table的字段要和ModelList的字段一样