Convert DataTable to List

后端 未结 14 1806
挽巷
挽巷 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:52

    That pretty works!!

    I made some updates from @suneelsarraf's answer and I removed Convert.ChangeType() because it keeps throwing Invalid Cast Exception. Have a take a look!

    #region *** Convert DT to List ***
    
        private List ConvertTo(DataTable datatable) where I : class
        {
            List lstRecord = new List();
            try
            {
                List columnsNames = new List();
                foreach (DataColumn DataColumn in datatable.Columns)
                    columnsNames.Add(DataColumn.ColumnName);
                lstRecord = datatable.AsEnumerable().ToList().ConvertAll(row => GetObject(row, columnsNames));
                return lstRecord;
            }
            catch
            {
                return lstRecord;
            }
    
        }
    
        private I GetObject(DataRow row, List columnsName) where I : class
        {
            I obj = (I)Activator.CreateInstance(typeof(I));
            try
            {
                PropertyInfo[] Properties = typeof(I).GetProperties();
                foreach (PropertyInfo objProperty in Properties)
                {
                    string columnname = columnsName.Find(name => name.ToLower() == objProperty.Name.ToLower());
                    if (!string.IsNullOrEmpty(columnname))
                    {
                        object dbValue = row[columnname];
                        if (dbValue != DBNull.Value)
                        {
                            if (Nullable.GetUnderlyingType(objProperty.PropertyType) != null)
                            {
                                objProperty.SetValue(obj, Convert.ChangeType(dbValue, Type.GetType(Nullable.GetUnderlyingType(objProperty.PropertyType).ToString())), null);
                            }
                            else
                            {
                                objProperty.SetValue(obj, Convert.ChangeType(dbValue, Type.GetType(objProperty.PropertyType.ToString())), null);
                            }
                        }
                    }
                }
                return obj;
            }
            catch(Exception ex)
            {
                return obj;
            }
        }
    
        #endregion
    
    

    And this is how you use in your code.

    // Other Codes Here
    var lstResult = ConvertTo(dataTableName); // Convert DT to List
    

    Have Fun! Be Safe in 2020.

    提交回复
    热议问题