将集合类转换成DataTable
/// 将集合类转换成DataTable
/// </summary>
/// <param name="list">集合</param>
/// <returns></returns>
public static DataTable ToDataTable(IList list)
{
DataTable result = new DataTable();
if (list.Count > 0)
{
PropertyInfo[] propertys = list[0].GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
Type colType = pi.PropertyType; if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>))) //避免空值报错
{
colType = colType.GetGenericArguments()[0];
}
if (pi.Name != "DataTable_Action_") //避免列要求有效的 DataType错误,主要是针对自定义数据类型
{
result.Columns.Add(new DataColumn(pi.Name, colType));
}
}
for (int i = 0; i < list.Count; i++)
{
ArrayList tempList = new ArrayList();
foreach (PropertyInfo pi in propertys)
{
if (pi.Name != "DataTable_Action_")//避免列要求有效的 DataType错误,主要是针对自定义数据类型
{
object obj = pi.GetValue(list[i], null) == null ? DBNull.Value : pi.GetValue(list[i], null); //避免空值报错
//object obj = pi.GetValue(list[i], null);
tempList.Add(obj);
}
}
object[] array = tempList.ToArray();
result.LoadDataRow(array, true);
}
}
return result;
}