The datatable
In .NET, you may encounter a scene that needs to convert the generic list or enumerated object to the DataTable object. Although there is no built -in static method, this conversion can be performed, and multiple methods can be used.
Use FastMember
In the .NET Framework 4.5 or higher version, you can use the FastMember library in Nuget. This library provides high -performance meta -programming functions:
1 2 3 4 5 6 7 8 9 | using FastMember;
using System.Data;
IEnumerable<sometype> data = ...;
DataTable table = new DataTable();
using ( var reader = ObjectReader.Create(data))
{
table.Load(reader);
}
|
Copy after login
Use reflection <<>
Before the .NET Framework 4.5, you can use the reflection to create DataTable dynamically from the generic list. Compared with FastMember, this is a low -efficiency method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | public static DataTable ToDataTable<T>(this IList<T> data)
{
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
for (int i = 0; i < props. Count ; i++)
{
PropertyDescriptor prop = props[i];
table.Columns.Add(prop.Name, prop.PropertyType);
}
foreach (T item in data)
{
DataRow row = table.NewRow();
for (int i = 0; i < props. Count ; i++)
{
row[i] = props[i].GetValue(item);
}
table.Rows.Add(row);
}
return table;
}
|
Copy after login
This function can call any generic list to generate a datatable based on a list object attribute.
Performance Precautions
FastMember method is much faster than reflected methods. However, the performance of DataTable still has room for improvement, because its performance characteristics may vary according to factors such as data volume and number of columns.
The above is the detailed content of How Can I Efficiently Convert Generic Lists to DataTables in .NET?. For more information, please follow other related articles on the PHP Chinese website!