Home >Backend Development >C++ >How to Efficiently Convert Generic Lists to DataTables in C#?
Many C# developers encounter the challenge of converting generic lists to DataTables. While reflection offers a solution, more efficient methods exist. This article explores optimal approaches.
For superior performance, the FastMember library (available via NuGet) is highly recommended:
<code class="language-csharp">IEnumerable<sometype> data = ...; DataTable table = new DataTable(); using(var reader = ObjectReader.Create(data)) { table.Load(reader); }</code>
Prior to .NET 3.5, developers relied on reflection or HyperDescriptor (available in .NET 2.0):
<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>
To maximize performance, enabling HyperDescriptor for the object type is crucial. Benchmark tests reveal substantial speed improvements:
By utilizing these techniques, developers can significantly enhance the efficiency of converting generic lists to DataTables in their C# applications.
The above is the detailed content of How to Efficiently Convert Generic Lists to DataTables in C#?. For more information, please follow other related articles on the PHP Chinese website!