converting DataTable to List (ProjectDracula)

前端 未结 2 825
时光说笑
时光说笑 2020-12-21 11:38

I need a static method to convert DataTables(dynamic) to List(again dynamic Entity) here is my code help would be appereciated

        public static ICollect         


        
2条回答
  •  [愿得一人]
    2020-12-21 12:28

    private static List ConvertDataTable(DataTable dt)  
    {  
        List data = new List();  
        foreach (DataRow row in dt.Rows)  
        {  
            T item = GetItem(row);  
            data.Add(item);  
        }  
        return data;  
    }
    
    private static T GetItem(DataRow dr)  
    {  
        Type temp = typeof(T);  
        T obj = Activator.CreateInstance();  
    
        foreach (DataColumn column in dr.Table.Columns)  
        {  
            foreach (PropertyInfo pro in temp.GetProperties())  
            {  
                if (pro.Name == column.ColumnName)  
                    pro.SetValue(obj, dr[column.ColumnName], null);  
                else  
                    continue;  
            }  
        }  
        return obj;  
    } 
    

    Usage:

    List< Student > studentDetails = new List();  
    studentDetails = ConvertDataTable(dt);
    

    Source: http://www.c-sharpcorner.com/UploadFile/ee01e6/different-way-to-convert-datatable-to-list/

提交回复
热议问题