list转datatable
时间: 2023-09-16 20:16:19 浏览: 86
list转换为dataTable
要将List转换为DataTable,可以使用以下代码实现:
```
public DataTable ListToDataTable<T>(List<T> list)
{
DataTable dataTable = new DataTable();
PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
dataTable.Columns.Add(property.Name, property.PropertyType);
}
foreach (T item in list)
{
DataRow dataRow = dataTable.NewRow();
foreach (PropertyInfo property in properties)
{
dataRow[property.Name = property.GetValue(item);
}
dataTable.Rows.Add(dataRow);
}
return dataTable;
}
```
这个方法接受一个List作为参数,并使用反射来获取List中对象的属性信息。然后,它创建一个DataTable对象,并根据属性信息添加列。接下来,它遍历List中的每个对象,创建一个DataRow对象,并将属性值赋给相应的列。最后,将DataRow添加到DataTable中,最终返回转换后的DataTable。<span class="em">1</span><span class="em">2</span>
#### 引用[.reference_title]
- *1* [List转DataTable并导出为Excel](https://download.csdn.net/download/vouyv/9512300)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *2* [DataTable转换为List的通用方法](https://blog.csdn.net/runAndRun/article/details/12519663)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文