How to convert datatable to generic list c#

How to convert datatable to generic list c#

 

List<DataRow> lst = new List<DataRow>(dt.Select());

 

through extension method

 

public static List<T> tolist<T>(this DataTable dt)
{
    const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
    var columnNames = dt.Columns.Cast<DataColumn>()
        .Select(c => c.ColumnName)
        .ToList();
    var objectProperties = typeof(T).GetProperties(flags);
    var result = dt.AsEnumerable().Select(dataRow =>
    {
        var instance = Activator.CreateInstance<T>();

        foreach (var properties in objectProperties.Where(properties => columnNames.Contains(properties.Name) && dataRow[properties.Name] != DBNull.Value))
        {
            properties.SetValue(instanceOfT, dataRow[properties.Name], null);
        }
        return instance;
    }).ToList();

    return result ;
}


var output = yourDataInstance.tolist<targetModelType>();

2021-10-03