/// DataTable转换为List<Model>;
/// </summary>
/// <typeparam name="T"></typeparam>
public static class DataTableToListModel<T> where T : new()
{
public static IList<T> ConvertToModel(DataTable dt)
{
//定义集合
List<T> ts = new List<T>();
string tempName = "";
T t = new T();
PropertyInfo[] propertys = t.GetType().GetProperties();
foreach (DataRow row in dt.Rows)
{
t = new T();
foreach (PropertyInfo pi in propertys)
{
tempName = pi.Name;
if (dt.Columns.Contains(tempName))
{
if (!pi.CanWrite)
continue;
object value = row[tempName];
if (value != DBNull.Value)
pi.SetValue(t, value, null);
}
}
ts.Add(t);
}
return ts;
}
}
public class user {
private int id;
public int Id
{
get { return id; }
set { id = value; }
}
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
}
//调用:
List<user> ilist= Web.DataTableToListModel<user>.ConvertToModel(dt);