<.> In the .NET, the list was converted into a data table
In the .NET development, converting generic lists into data tables is a common demand. The following is how to use FastMember to implement this operation:
Fastmember's meta -programming API optimized this process to achieve maximum performance. You can specify a specific member you want to include:
<code class="language-csharp">using FastMember; IEnumerable<sometype> data = ...; DataTable table = new DataTable(); using (var reader = ObjectReader.Create(data)) { table.Load(reader); }</code>
Alternative method
<code class="language-csharp">using FastMember; IEnumerable<sometype> data = ...; DataTable table = new DataTable(); using (var reader = ObjectReader.Create(data, "Id", "Name", "Description")) { table.Load(reader); }</code>
reflection
In order to improve performance, you can enable Hyperdescriptor:
<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++) { PropertyDescriptor prop = props[i]; row[i] = prop.GetValue(item); } table.Rows.Add(row); } return table; }</code>
The above is the detailed content of How Can I Efficiently Convert Lists to DataTables in .NET?. For more information, please follow other related articles on the PHP Chinese website!