在開發微信小程序的API獲取多條數據時,會遇到返回DataTable對象的數據,但前端無法接收這個類型的數據,需要轉化爲List數組對象。由此,需要參考網絡上的各類資料,編寫了一個泛型的方法,具體代碼如下:
/// <summary>
/// 將Table數據轉換爲List模型集合
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static IList<T> TableToListModel<T>(DataTable dt)
where T : new()
{
IList<T> ts = new List<T>();// 定義集合
Type type = typeof(T); // 獲得此模型的類型
foreach (DataRow dr in dt.Rows)
{
T t = new T();
PropertyInfo[] propertys = t.GetType().GetProperties();// 獲得此模型的公共屬性
foreach (PropertyInfo pi in propertys)
{
//獲取屬性名稱
String name = pi.Name;
if (dr.Table.Columns.Contains(name))
{
//非泛型
if (!pi.PropertyType.IsGenericType)
{
pi.SetValue(t, string.IsNullOrEmpty(dr[name].ToString()) ? null : Convert.ChangeType(dr[name], pi.PropertyType), null);
}
//泛型Nullable<>
else
{
Type genericTypeDefinition = pi.PropertyType.GetGenericTypeDefinition();
//model屬性是可爲null類型,進行賦null值
if (genericTypeDefinition == typeof(Nullable<>))
{
//返回指定可以爲 null 的類型的基礎類型參數
pi.SetValue(t, string.IsNullOrEmpty(dr[name].ToString()) ? null : Convert.ChangeType(dr[name], Nullable.GetUnderlyingType(pi.PropertyType)), null);
}
}
}
}
ts.Add(t);
}
return ts;
}
參考文章:[C#] DataTable轉成List集合,只是這篇文章中的以下代碼,無法將bigint類型的字段轉化爲string類型,親測。
然後,int類型轉string同理,未測。
if (value != DBNull.Value)
pi.SetValue(t, value, null);
歡迎指正。