How do you convert a DataTable into a generic list?

前端 未结 27 2550
后悔当初
后悔当初 2020-11-22 17:04

Currently, I\'m using:

DataTable dt = CreateDataTableInSomeWay();

List list = new List(); 
foreach (DataRow dr in dt.Rows)
{
          


        
相关标签:
27条回答
  • 2020-11-22 17:30

    Again, using 3.5 you may do it like:

    dt.Select().ToList()
    

    BRGDS

    0 讨论(0)
  • DataTable dt;   // datatable should contains datacolumns with Id,Name
    
    List<Employee> employeeList=new List<Employee>();  // Employee should contain  EmployeeId, EmployeeName as properties
    
    foreach (DataRow dr in dt.Rows)
    {
        employeeList.Add(new Employee{EmployeeId=dr.Id,EmplooyeeName=dr.Name});
    }
    
    0 讨论(0)
  • 2020-11-22 17:30

    you can use following two Generic functions

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

    and use it as following

    List<StudentScanExamsDTO> studentDetails = ConvertDataTable<StudentScanExamsDTO>(dt);
    
    0 讨论(0)
  • 2020-11-22 17:31
            /* This is a generic method that will convert any type of DataTable to a List 
             * 
             * 
             * Example :    List< Student > studentDetails = new List< Student >();  
             *              studentDetails = ConvertDataTable< Student >(dt);  
             *
             * Warning : In this case the DataTable column's name and class property name
             *           should be the same otherwise this function will not work properly
             */
    

    The following are the two functions in which if we pass a DataTable and a user defined class. It will then return the List of that class with the DataTable data.

            public static List<T> ConvertDataTable<T>(DataTable dt)
            {
                List<T> data = new List<T>();
                foreach (DataRow row in dt.Rows)
                {
                    T item = GetItem<T>(row);
                    data.Add(item);
                }
                return data;
            }
    
    
            private static T GetItem<T>(DataRow dr)
            {
                Type temp = typeof(T);
                T obj = Activator.CreateInstance<T>();
    
                foreach (DataColumn column in dr.Table.Columns)
                {
                    foreach (PropertyInfo pro in temp.GetProperties())
                    {
                       //in case you have a enum/GUID datatype in your model
                       //We will check field's dataType, and convert the value in it.
                        if (pro.Name == column.ColumnName){                
                        try
                        {
                            var convertedValue = GetValueByDataType(pro.PropertyType, dr[column.ColumnName]);
                            pro.SetValue(obj, convertedValue, null);
                        }
                        catch (Exception e)
                        {         
                           //ex handle code                   
                            throw;
                        }
                            //pro.SetValue(obj, dr[column.ColumnName], null);
                    }
                        else
                            continue;
                    }
                }
                return obj;
            }
    

    This method will check the datatype of field, and convert dataTable value in to that datatype.

        private static object GetValueByDataType(Type propertyType, object o)
        {
            if (o.ToString() == "null")
            {
                return null;
            }
            if (propertyType == (typeof(Guid)) || propertyType == typeof(Guid?))
            {
                return Guid.Parse(o.ToString());
            }
            else if (propertyType == typeof(int) || propertyType.IsEnum) 
            {
                return Convert.ToInt32(o);
            }
            else if (propertyType == typeof(decimal) )
            {
                return Convert.ToDecimal(o);
            }
            else if (propertyType == typeof(long))
            {
                return Convert.ToInt64(o);
            }
            else if (propertyType == typeof(bool) || propertyType == typeof(bool?))
            {
                return Convert.ToBoolean(o);
            }
            else if (propertyType == typeof(DateTime) || propertyType == typeof(DateTime?))
            {
                return Convert.ToDateTime(o);
            }
            return o.ToString();
        }
    

    To call the preceding method, use the following syntax:

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

    Change the Student class name and dt value based on your requirements. In this case the DataTable column's name and class property name should be the same otherwise this function will not work properly.

    0 讨论(0)
  • 2020-11-22 17:33
    using System.Data;
    
    
    var myEnumerable = myDataTable.AsEnumerable();
    
    List<MyClass> myClassList =
        (from item in myEnumerable
         select new MyClass{
             MyClassProperty1 = item.Field<string>("DataTableColumnName1"),
             MyClassProperty2 = item.Field<string>("DataTableColumnName2")
        }).ToList();
    
    0 讨论(0)
  • 2020-11-22 17:33

    We can use a Generic Method for converting DataTable to List instead of manually converting a DataTable to List.

    Note: DataTable's ColumnName and Type's PropertyName should be same.

    Call the below Method:

    long result = Utilities.ConvertTo<Student>(dt ,out listStudent);
    
    // Generic Method
    public class Utilities
    {
        public static long ConvertTo<T>(DataTable table, out List<T> entity)
        {
            long returnCode = -1;
            entity = null;
    
            if (table == null)
            {
                return -1;
            }
    
            try
            {
                entity = ConvertTo<T>(table.Rows);
                returnCode = 0;
            }
    
            catch (Exception ex)
            {
                returnCode = 1000;
            }
    
            return returnCode;
        }
    
        static List<T> ConvertTo<T>(DataRowCollection rows)
        {
            List<T> list = null;
            if (rows != null)
            {
                list = new List<T>();
    
                foreach (DataRow row in rows)
                {
                    T item = CreateItem<T>(row);
                    list.Add(item);
                }
            }
    
            return list;
        }
    
        static T CreateItem<T>(DataRow row)
        {
            string str = string.Empty;
            string strObj = string.Empty;
    
            T obj = default(T);
    
            if (row != null)
            {
                obj = Activator.CreateInstance<T>();
                strObj = obj.ToString();
                NameValueCollection objDictionary = new NameValueCollection();
    
                foreach (DataColumn column in row.Table.Columns)
                {
                    PropertyInfo prop = obj.GetType().GetProperty(column.ColumnName);
    
                    if (prop != null)
                    {
                        str = column.ColumnName;
    
                        try
                        {
                            objDictionary.Add(str, row[str].ToString());
                            object value = row[column.ColumnName];
                            Type vType = obj.GetType();
    
                            if (value == DBNull.Value)
                            {
                                if (vType == typeof(int) || vType == typeof(Int16)
                                                         || vType == typeof(Int32)
                                                         || vType == typeof(Int64)
                                                         || vType == typeof(decimal)
                                                         || vType == typeof(float)
                                                         || vType == typeof(double))
                                {
                                    value = 0;
                                }
    
                                else if (vType == typeof(bool))
                                {
                                    value = false;
                                }
    
                                else if (vType == typeof(DateTime))
                                {
                                    value = DateTime.MaxValue;
                                }
    
                                else
                                {
                                    value = null;
                                }
    
                                prop.SetValue(obj, value, null);
                            }
    
                            else
                            {
                                prop.SetValue(obj, value, null);
                            }
                        }
    
                        catch(Exception ex)
                        {
    
                        }
                    }
                }
    
                PropertyInfo ActionProp = obj.GetType().GetProperty("ActionTemplateValue");
    
                if (ActionProp != null)
                {
                    object ActionValue = objDictionary;
                    ActionProp.SetValue(obj, ActionValue, null);
                }
            }
    
            return obj;
        }
    }
    
    0 讨论(0)
提交回复
热议问题