C# - IEnumerable<T> to DataTable

By , 7/11/2015
(0 ratings)
This Extension method builds a DataTable from an existing IEnumerable<T>. All data of public instance properties will be transferred.

Required Namespaces
System.Collections.Generic
System.Data
System.Reflection
Translate to VB
/// <summary>
/// This method builds a <see cref="System.Data.DataTable"/> from the existing source list.
/// </summary>
/// <typeparam name="T">The type of the items inside the source parameter. All instance properties of this type will be transferred.</typeparam>
/// <param name="source">The source list.</param>
/// <returns>A <see cref="System.Data.DataTable"/> with the data of <paramref name="source"/>.</returns>
public static DataTable ToDataTable<T>(this IEnumerable<T> source)
{
    var table = new DataTable();

    int i = 0;
    var props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
    foreach (var prop in props)
    {
        table.Columns.Add(new DataColumn(prop.Name, prop.PropertyType));
        ++i;
    }

    foreach (var item in source)
    {
        var values = new object[i];
        i = 0;
        foreach (var prop in props)
            values[i++] = prop.GetValue(item);
        table.Rows.Add(values);
    }

    return table;
}
Tagged with DataTable, LINQ, Converter.

Comments

 

Log in, to comment!