datable轉化成list
阿新 • • 發佈:2019-02-06
方式一:
public static List<T> ToList<T>(this DataTable dt)
{
var columnNames = dt.Columns.Cast<DataColumn>()
.Select(c => c.ColumnName)
.ToList();
var properties = typeof(T).GetProperties();
return dt.AsEnumerable().Select(row =>
{
var objT = Activator.CreateInstance<T>();
foreach (var pro in properties)
{
if (columnNames.Contains(pro.Name))
pro.SetValue(objT, row[pro.Name] == DBNull.Value ? string.Empty : row[pro.Name].ToString(), null);
}
return objT;
}).ToList();
}
方式二:
利用newtonsoft.json檔案將dataTable轉換成json資料格式,然後再轉換成list
public static List<T> ToList<T>(this DataTable dt)
{
var columnNames = dt.Columns.Cast<DataColumn>()
.Select(c => c.ColumnName)
.ToList();
var properties = typeof(T).GetProperties();
return dt.AsEnumerable().Select(row =>
{
var objT = Activator.CreateInstance<T>();
foreach (var pro in properties)
{
if (columnNames.Contains(pro.Name))
pro.SetValue(objT, row[pro.Name] == DBNull.Value ? string.Empty : row[pro.Name].ToString(), null);
}
return objT;
}).ToList();
}
方式二:
利用newtonsoft.json檔案將dataTable轉換成json資料格式,然後再轉換成list