Convert DataTable to List

后端 未结 14 1763
挽巷
挽巷 2020-12-04 12:09

I have an strongly typed DataTable of type MyType, I\'d like convert it in a List.

How can I do this ?

Thanks.

相关标签:
14条回答
  • 2020-12-04 12:56

    please try this code:

    public List<T> ConvertToList<T>(DataTable dt)
    {
        var columnNames = dt.Columns.Cast<DataColumn>()
            .Select(c => c.ColumnName)
            .ToList();
        var properties = typeof(T).GetProperties();
        return dt.AsEnumerable().Select(row =>
        {
            var objT = Activator.CreateInstance<T>();
            foreach (var pro in properties)
            {
                if (columnNames.Contains(pro.Name))
                    pro.SetValue(objT, row[pro.Name]);
            }
            return objT;
        }).ToList();
    }
    
    0 讨论(0)
  • 2020-12-04 12:58

    Create a list with type<DataRow> by extend the datatable with AsEnumerable call.

    var mylist = dt.AsEnumerable().ToList();
    

    Cheers!! Happy Coding

    0 讨论(0)
提交回复
热议问题