<span style="white-space:pre"> </span>/// <summary>
/// 將DataTable數據根據列名和屬性名是否相同轉換成List集合,屬性名列名區分大小寫
/// </summary>
/// <typeparam name="T">要返回的集合類型</typeparam>
/// <param name="table">源數據</param>
/// <returns>轉換後的集合數據</returns>
public static List<T> TableToModels<T>(this DataTable table) where T : new()
{
List<T> list = new List<T>();
List<string> Properties = typeof(T).GetProperties().Select(p => p.Name).ToList();
if (table != null && table.Rows.Count > 0)
{
foreach (DataRow row in table.Rows)
{
T t = new T();
foreach (DataColumn col in table.Columns)
{
if (Properties.Contains(col.ColumnName) && row[col.ColumnName] != DBNull.Value)
{
var prop = typeof(T).GetProperty(col.ColumnName);
prop.SetValue(t, row[col.ColumnName], null);
}
}
list.Add(t);
}
}
return list;
}
/// <summary>
/// 將T與F的同名屬性賦值給F的一個實例並返回,屬性名區分大小寫
/// </summary>
/// <typeparam name="T">類型T</typeparam>
/// <typeparam name="F">轉換的目標類型F</typeparam>
/// <param name="t">原來的類實例</param>
/// <returns>新的類實例</returns>
public static F ModelToModel<T, F>(this T t)
where T : new()
where F : new()
{
F f = new F();
System.Reflection.PropertyInfo[] tProperties = typeof(T).GetProperties();
List<string> fPropertiesName = typeof(F).GetProperties().Select(p => p.Name).ToList();
foreach (var proper in tProperties)
{
if (fPropertiesName.Contains(proper.Name) && proper.GetValue(t, null) != DBNull.Value && proper.GetValue(t, null) != null)
{
var prop = typeof(F).GetProperty(proper.Name);
prop.SetValue(f, proper.GetValue(t, null), null);
}
}
return f;
}