C# 中DataTable转成模型List

时间:2023-03-09 18:58:15
C# 中DataTable转成模型List

C# 中DataTable转成模型List

引入using System.Reflection; 命名空间

使用注意实体类的属性名必须和DataTable的列名一致

使用:

DBList<StorageReport> dblist = new DBList<StorageReport>(dt);

模型:

    public class StorageReport
{
public string pqty { get; set; }
public string dqty { get; set; }
public string sqty { get; set; }
}

代码:

    public class DBList<T>:List<T> where T:new()
{
public DBList(DataTable dt)
{
foreach (T value in getItemValue<T>(dt))
{
this.Add(value);
}
} private List<T> getItemValue<T>(DataTable dt) where T : new()
{
List<T> items = new List<T>();
T model = new T(); //取出所有属性字段
PropertyInfo[] propertys = model.GetType().GetProperties();
foreach (DataRow dr in dt.Rows)
{
T item = new T();
foreach (PropertyInfo pinfo in propertys)
{
string value = dt.Columns.Contains(pinfo.Name) ? dr[pinfo.Name].ToString() : "";
pinfo.SetValue(item, value, null);
}
items.Add(item);
}
return items;
}
}