Fastest way to convert datatable to generic list

后端 未结 6 719
逝去的感伤
逝去的感伤 2020-12-01 15:30

I have a data tier select method that returns a datatable. It\'s called from a business tier method that should then return a strongly typed generic List.

What I wa

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 15:55

    I know this answer is very late but i spent an hour and above to prepare this code because i needed this first then i thought some one in search of a solution for this question may get use of this..

    Inorder for my answer to work correctly, you need to have same names for your list properties as in the DataBase table-columns(fields) or the DataTable column names.

    Solution:

    public List GetListFromDT(Type className, DataTable dataTable)
            {
                List list = new List();
                foreach (DataRow row in dataTable.Rows)
                {
                    object objClass = Activator.CreateInstance(className);
                    Type type = objClass.GetType();
                    foreach (DataColumn column in row.Table.Columns)
                    {
                        PropertyInfo prop = type.GetProperty(column.ColumnName);
                        prop.SetValue(objClass, row[column.ColumnName], null);   
                    }
                    list.Add(objClass);
                }
                return list;
            }
    

    How to use ?

    Lets say you have a values populated datatable named dtPersons

    DataTable dtPersons; //populate this datatable
    

    Then lets say you have a class with the following properties.

    public class Persons{
        public string Name {get; set;}
        public int Age {get; set;}
    }
    

    Now pack and put the method in your model. call the method as below.

    List dynamicListReturned = GetListFromDT(typeof(Persons), dataTable);
    List listPersons = dynamicListReturned.Cast().ToList();
    

    That's it now you got your list from the datatable in listPersons.

    Remember: Both the names in the class properties and the DataTable/Database should be the same

提交回复
热议问题