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;
}

 

posted @ 2012-04-22 17:33  VipSoft  阅读(206)  评论(0编辑  收藏  举报