Home > Backend Development > C++ > How to Efficiently Convert Generic Lists to DataTables in C#?

How to Efficiently Convert Generic Lists to DataTables in C#?

Mary-Kate Olsen
Release: 2025-01-30 21:41:12
Original
585 people have browsed it

How to Efficiently Convert Generic Lists to DataTables in C#?

Efficiently Transforming Generic Lists into 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.

Leveraging FastMember for Speed

For superior performance, the FastMember library (available via NuGet) is highly recommended:

IEnumerable<sometype> data = ...;
DataTable table = new DataTable();
using(var reader = ObjectReader.Create(data)) {
    table.Load(reader);
}
Copy after login

Pre-.NET 3.5 Alternatives: Reflection and HyperDescriptor

Prior to .NET 3.5, developers relied on reflection or HyperDescriptor (available in .NET 2.0):

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

Performance Optimization: HyperDescriptor

To maximize performance, enabling HyperDescriptor for the object type is crucial. Benchmark tests reveal substantial speed improvements:

  • Standard Method: 27179 ms
  • HyperDescriptor Enabled: 6997 ms

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template