Home >Backend Development >C++ >How Can I Efficiently Convert an IEnumerable to a DataTable in C#?

How Can I Efficiently Convert an IEnumerable to a DataTable in C#?

Susan Sarandon
Susan SarandonOriginal
2025-01-20 00:27:09335browse

How Can I Efficiently Convert an IEnumerable to a DataTable in C#?

Efficiently convert IEnumerable to DataTable in C#

Converting IEnumerable to DataTable allows developers to process data in a structured tabular format. However, existing solutions often rely on inefficient reflection-based approaches. This question seeks to find a more efficient alternative.

First, the code snippet in the provided answer provides a useful extension method:

<code class="language-csharp">public static DataTable ToDataTable<T>(this IEnumerable<T> items)
{
    // 使用类型名称初始化DataTable
    var table = new DataTable(typeof(T).Name);

    // 获取类型的公共属性
    PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

    // 将属性作为列添加到DataTable
    foreach (var property in properties)
    {
        var propertyType = property.PropertyType;

        // 处理可空类型
        if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
        {
            propertyType = Nullable.GetUnderlyingType(propertyType);
        }

        table.Columns.Add(property.Name, propertyType);
    }

    // 将每个T的属性值作为行添加到DataTable
    foreach (var item in items)
    {
        var values = new object[properties.Length];
        for (int i = 0; i < properties.Length; i++)
        {
            values[i] = properties[i].GetValue(item);
        }
        table.Rows.Add(values);
    }

    return table;
}</code>

This extension method provides a convenient and efficient way to convert IEnumerable to a DataTable. By carefully handling nullable types, it ensures data integrity and allows values ​​to be retrieved using strongly typed column names.

The above is the detailed content of How Can I Efficiently Convert an IEnumerable 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