ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

Datatable to List

Datatable to List

Source

public static List<T> ToList<T>(this DataTable table) where T : class, new()
{
    try
    {
        List<T> list = new List<T>();

        foreach (var row in table.AsEnumerable())
        {
            T obj = new T();

            foreach (var prop in obj.GetType().GetProperties())
            {
                try
                {
                    PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name);
                    propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null);
                }
                catch
                {
                    continue;
                }
            }

            list.Add(obj);
        }

        return list;
    }
    catch
    {
        return null;
    }
}

Example

var myList = dt.ToList();

Author: Keyur Panchal

Submitted on: 11 aug. 2015

Language: C#

Type: datatavle, List

Views: 8268