public static DataTable ToDataTable<T>(this IEnumerable<T> list)
{
DataTable dataTable = new DataTable();
PropertyInfo[] array = null;
foreach (T item in list)
{
if (array == null)
{
array = item.GetType().GetProperties();
PropertyInfo[] array2 = array;
foreach (PropertyInfo propertyInfo in array2)
{
Type type = propertyInfo.PropertyType;
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
type = type.GetGenericArguments()[0];
}
dataTable.Columns.Add(new DataColumn(propertyInfo.Name, type));
}
}
DataRow dataRow = dataTable.NewRow();
PropertyInfo[] array3 = array;
foreach (PropertyInfo propertyInfo2 in array3)
{
dataRow[propertyInfo2.Name] = ((propertyInfo2.GetValue(item, null) == null) ? DBNull.Value : propertyInfo2.GetValue(item, null));
}
dataTable.Rows.Add(dataRow);
}
return dataTable;
}
C# IEnumerable<T>转换成DataTable
于 2023-11-09 15:38:29 首次发布