List<T> to DataTable

/// <summary>
/// 集合装换DataTable
/// </summary>
/// <param name="list">集合</param>
/// <returns></returns>
public static DataTable ToDataTable(IList list)
{
 var dataTable = new DataTable();
 if (list.Count > 0)
 {
  PropertyInfo[] propertys = list[0].GetType().GetProperties();
  foreach (PropertyInfo pi in propertys)
  {
   dataTable.Columns.Add(pi.Name, pi.PropertyType);
  }
  for (int i = 0; i < list.Count; i++)
  {
   ArrayList tempList = new ArrayList();
   foreach (PropertyInfo pi in propertys)
   {
    object obj = pi.GetValue(list[i], null);
    tempList.Add(obj);
   }
   object[] array = tempList.ToArray();
   dataTable.LoadDataRow(array, true);
  }
 }
 return dataTable;
}
原文地址:https://www.cnblogs.com/vipsoft/p/2465240.html