ILIST和datatable可以互相变换吗
时间: 2023-11-21 17:05:33 浏览: 48
是的,可以将IList和DataTable对象互相转换。以下是示例代码:
1. 将IList转换为DataTable
```csharp
using System.Data;
using System.Reflection;
public static DataTable ConvertToDataTable<T>(IList<T> list)
{
DataTable table = new DataTable();
PropertyInfo[] properties = typeof(T).GetProperties();
foreach (PropertyInfo property in properties)
{
table.Columns.Add(property.Name, property.PropertyType);
}
foreach (T item in list)
{
DataRow row = table.NewRow();
foreach (PropertyInfo property in properties)
{
row[property.Name] = property.GetValue(item, null);
}
table.Rows.Add(row);
}
return table;
}
```
在上面的代码中,将使用反射获取数据模型的属性信息,创建一个DataTable对象,并将属性名作为DataTable的列名。然后将IList中的数据逐一转换为DataRow对象,并将DataRow对象添加到DataTable中。最终返回DataTable对象作为结果。
2. 将DataTable转换为IList
```csharp
using System.Collections.Generic;
using System.Data;
public static IList<T> ConvertToList<T>(DataTable table) where T : new()
{
IList<T> list = new List<T>();
foreach (DataRow row in table.Rows)
{
T item = new T();
foreach (DataColumn column in table.Columns)
{
PropertyInfo property = typeof(T).GetProperty(column.ColumnName);
if (property != null && row[column] != DBNull.Value)
{
property.SetValue(item, row[column], null);
}
}
list.Add(item);
}
return list;
}
```
在上面的代码中,将使用反射获取数据模型的属性信息,创建一个IList对象,并将DataTable中的每一行转换为数据模型对象。最终返回IList对象作为结果。
需要注意的是,IList对象中的属性名应该与DataTable中的列名一致,否则可能会出现转换失败的情况。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![cs](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)