/// <summary>
/// 实体对象转换DataTable
/// </summary>
/// <param name="entity">实体对象</param>
/// <returns>DataTable</returns>
public static DataTable GetDataTableByEntity(object entity)
{
DataTable dt = new DataTable();
Type type = entity.GetType();
dt.TableName = type.Name;
DataRow dr = dt.NewRow();
foreach (var p in type.GetProperties())
{
if (!dt.Columns.Contains(p.Name))
dt.Columns.Add(p.Name);
dr[p.Name] = p.GetValue(entity, null) == null ? "" : p.GetValue(entity, null).ToString();
}
dt.Rows.Add(dr);
return dt;
}
/// <summary>
/// List转换成DataTable
/// </summary>
/// <typeparam name="T">实体对象类型</typeparam>
/// <param name="list">list集合</param>
/// <returns>DataTable</returns>
public static DataTable GetDataTableByList<T>(List<T> list)
{
DataTable dt = new DataTable();
foreach (T t in list)
{
DataRow dr = dt.NewRow();
Type type = t.GetType();
if (String.IsNullOrEmpty(dt.TableName))
dt.TableName = type.Name;
foreach (var p in type.GetProperties())
{
if (!dt.Columns.Contains(p.Name))
dt.Columns.Add(p.Name);
dr[p.Name] = p.GetValue(t, null) == null ? "" : p.GetValue(t, null).ToString();
}
dt.Rows.Add(dr);
}
return dt;
}