///
<summary>
/// DataTable轉換為List<Model>
/// </summary>
public static class DataTableToListModel<T> where T : new ()
{
public static IList<T> ConvertToModel(DataTable dt)
{
// 定義集合
IList<T> ts = new List<T>();
T t = new T();
string tempName = "" ;
// 獲取此模型的公共屬性
PropertyInfo[] propertys = t.GetType().GetProperties();
foreach (DataRow row in dt.Rows)
{
t = new T();
foreach (PropertyInfo pi in propertys)
{
tempName = pi.Name;
// 檢查DataTable是否包含此列
if (dt.Columns.Contains(tempName))
{
// 判斷此屬性是否有set
if (!pi.CanWrite)
continue ;
object value = row[tempName];
if (value != DBNull.Value)
pi.SetValue(t, value, null );
}
}
ts.Add(t);
}
return ts;
}
}
/// DataTable轉換為List<Model>
/// </summary>
public static class DataTableToListModel<T> where T : new ()
{
public static IList<T> ConvertToModel(DataTable dt)
{
// 定義集合
IList<T> ts = new List<T>();
T t = new T();
string tempName = "" ;
// 獲取此模型的公共屬性
PropertyInfo[] propertys = t.GetType().GetProperties();
foreach (DataRow row in dt.Rows)
{
t = new T();
foreach (PropertyInfo pi in propertys)
{
tempName = pi.Name;
// 檢查DataTable是否包含此列
if (dt.Columns.Contains(tempName))
{
// 判斷此屬性是否有set
if (!pi.CanWrite)
continue ;
object value = row[tempName];
if (value != DBNull.Value)
pi.SetValue(t, value, null );
}
}
ts.Add(t);
}
return ts;
}
}