C# DataTable转换成实体列表 与 实体列表转换成DataTable
时间: 2024-03-13 07:43:54 浏览: 145
c#中利用委托反射将DataTable转换为实体集的代码
将C# DataTable转换为实体列表可以使用以下代码:
```csharp
public static List<T> ConvertDataTableToList<T>(DataTable dataTable) where T : new()
{
List<T> list = new List<T>();
foreach (DataRow row in dataTable.Rows)
{
T obj = new T();
foreach (PropertyInfo propertyInfo in obj.GetType().GetProperties())
{
if (dataTable.Columns.Contains(propertyInfo.Name))
{
object value = row[propertyInfo.Name];
if (value != DBNull.Value)
{
propertyInfo.SetValue(obj, value, null);
}
}
}
list.Add(obj);
}
return list;
}
```
将实体列表转换为C# DataTable可以使用以下代码:
```csharp
public static DataTable ConvertListToDataTable<T>(List<T> list)
{
DataTable dataTable = new DataTable();
foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
{
dataTable.Columns.Add(propertyInfo.Name, Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType);
}
foreach (T obj in list)
{
DataRow row = dataTable.NewRow();
foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
{
row[propertyInfo.Name] = propertyInfo.GetValue(obj) ?? DBNull.Value;
}
dataTable.Rows.Add(row);
}
return dataTable;
}
```
阅读全文