Converting DataTable to Generic List

February 09, 2015 by Anuraj

.Net .Net 3.0 / 3.5 .Net 4.0 ASP.Net Windows Forms

Code snippet for converting a DataTable to Generic List.

public static List<TEntity> ToList<TEntity>(this DataTable dataTable,
    Dictionary<string, string> mapping) where TEntity : new()
{
    var list = new List<TEntity>();
    foreach (DataRow dataRow in dataTable.Rows)
    {
        var entity = new TEntity();
        foreach (var keyvaluePair in mapping)
        {
            var property = entity.GetType().GetProperty(keyvaluePair.Key,
                            BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
            if (dataRow[keyvaluePair.Value] != DBNull.Value)
            {
                var propertyType = 
                    Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
                var value = 
                    Convert.ChangeType(dataRow[keyvaluePair.Value], propertyType);
                property.SetValue(entity, value, null);
            }
        }

        list.Add(entity);
    }

    return list;
}

You can use this as an extension method to the Data Table class. By providing the mapping dictionary, the consumer class can decide which all columns / properties need to participate in the conversion.

Happy Programming :)

Copyright © 2024 Anuraj. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Powered by Jekyll. Hosted with ❤ by GitHub