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.
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:
<code class="language-csharp">using FastMember; using System.Data; IEnumerable<sometype> data = ...; DataTable table = new DataTable(); using (var reader = ObjectReader.Create(data)) { table.Load(reader); }</code>
<code class="language-csharp">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; }</code>
Performance Precautions
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!