C# List<T> 转DataTable
时间: 2023-12-10 20:02:51 浏览: 89
可以使用以下代码将 C# List<T> 转换成 DataTable:
```csharp
public static DataTable ToDataTable<T>(List<T> items)
{
DataTable dataTable = new DataTable(typeof(T).Name);
PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in props)
{
dataTable.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
}
foreach (T item in items)
{
DataRow row = dataTable.NewRow();
foreach (PropertyInfo prop in props)
{
row[prop.Name] = prop.GetValue(item, null) ?? DBNull.Value;
}
dataTable.Rows.Add(row);
}
return dataTable;
}
```
使用方法:
```csharp
List<MyClass> myList = new List<MyClass>();
// 填充 myList
DataTable dataTable = ToDataTable(myList);
```
阅读全文