how to turn a model list to a DataTable in Csharp
时间: 2024-05-06 22:19:17 浏览: 110
To convert a model list to a DataTable in C#, you can follow these steps:
1. Create a new DataTable object.
2. Use the DataTable.Columns.Add method to add columns to the DataTable based on the properties in your model class.
3. Loop through your model list, creating DataRow objects and adding them to the DataTable using the DataTable.Rows.Add method.
Here's an example code snippet that demonstrates how to do this:
```
public DataTable ConvertToDataTable<T>(IList<T> data)
{
DataTable table = new DataTable();
PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in props)
{
table.Columns.Add(prop.Name, prop.PropertyType);
}
foreach (T item in data)
{
DataRow row = table.NewRow();
foreach (PropertyInfo prop in props)
{
row[prop.Name] = prop.GetValue(item, null);
}
table.Rows.Add(row);
}
return table;
}
```
You can call this method by passing in your model list as a parameter:
```
List<MyModel> myModelList = new List<MyModel>();
// populate myModelList with data
DataTable dataTable = ConvertToDataTable(myModelList);
```
阅读全文