🌟 C中DataTable与List之间的转换方法 🌟
在C开发中,`DataTable`和`List
首先,从`DataTable`到`List
```csharp
var list = dataTable.AsEnumerable()
.Select(row => new MyModel {
Id = row.Field
Name = row.Field
}).ToList();
```
这段代码将`DataTable`中的每一行映射为一个对象,并存入`List
反过来,从`List
```csharp
public static DataTable ToDataTable
{
var table = new DataTable(typeof(T).Name);
var properties = typeof(T).GetProperties();
foreach (var prop in properties)
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
foreach (var item in items)
table.Rows.Add(properties.Select(p => p.GetValue(item)).ToArray());
return table;
}
```
这两种方法极大地提升了数据处理效率,无论是前端展示还是后端逻辑,都能游刃有余!💪
版权声明:本文由用户上传,如有侵权请联系删除!