list列表转换为 DataTable
/// <summary>
/// Convert List To Table
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
public static DataTable ListToDataTable<T>(List<T> entitys)
{
DataTable dt = new DataTable();
try
{
if (entitys != null)
{
Type entityType = entitys[0].GetType();
PropertyInfo[] entityProperties = entityType.GetProperties();
for (int i = 0; i < entityProperties.Length; i++)
{
//dt.Columns.Add(entityProperties[i].Name, entityProperties[i].PropertyType);
dt.Columns.Add(entityProperties[i].Name);
}
foreach (object entity in entitys)
{
if (entity.GetType() == entityType)
{
//throw new Exception("");
object[] entityValues = new object[entityProperties.Length];
for (int i = 0; i < entityProperties.Length; i++)
{
entityValues[i] = entityProperties[i].GetValue(entity, null);
}
dt.Rows.Add(entityValues);
}
}
}
}
catch (System.Exception ex)
{
if (ExceptionManager.HandleException(ex, ExceptionPolicyType.BusinessLayerPolicy))
throw;
}
return dt;
}