Home >Backend Development >C++ >How to Efficiently Convert a Generic List to a DataTable in C#?

How to Efficiently Convert a Generic List to a DataTable in C#?

Barbara Streisand
Barbara StreisandOriginal
2025-01-30 21:56:11929browse

How to Efficiently Convert a Generic List to a DataTable in C#?

C# medium high -efficiency converting the generic list into datatable

In software development, the data is often required in structured format. Datatable is a common data structure that provides data forms. However, you may encounter the situation where the data that needs to be processed is stored in the generic list or an enumeration object. In this case, a method is needed to convert the list or accessible object to DataTable.

Use FastMember to make efficient conversion

You can use the FastMember library on Nuget to obtain an efficient and convenient solution. Using FastMember, you can use the following code to execute the conversion:

Custom conversion realization

<code class="language-csharp">IEnumerable<sometype> data = ...;
DataTable table = new DataTable();
using (var reader = ObjectReader.Create(data))
{
    table.Load(reader);
}</code>

If you prefer the custom conversion method, you can use the HyperDescriptor function in reflection or .NET 2.0 to create DataTable from the list. This is an example implementation:

Performance precautions

<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>
When evaluating different conversion methods, it is necessary to consider performance effects. The FastMember solution provides the best speed due to its meta -programming function. Although custom implementation is slow, it is still an effective option for smaller data sets.

Conclusion

Converting the generic list or an enumeration object to DataTable is a common task in C# programming. By using the FastMember library or realizing custom conversion, developers can efficiently implement this conversion.

The above is the detailed content of How to Efficiently Convert a Generic List to a DataTable in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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