将一个DataTable转换成一个List的泛型集合

时间:2020-12-20 19:39:41

 protected List<T> DataTableToList<T>(DataTable dataTable)
        {
            List<T> list = new List<T>();
            Type targetType = typeof(T);
            PropertyInfo[] allPropertyArray = targetType.GetProperties();
            foreach (DataRow rowElement in dataTable.Rows)
            {
                T element = Activator.CreateInstance<T>();
                foreach (DataColumn columnElement in dataTable.Columns)
                {
                    foreach (PropertyInfo property in allPropertyArray)
                    {
                        if (property.Name.Equals(columnElement.ColumnName))
                        {
                            if (rowElement[columnElement.ColumnName] == DBNull.Value)
                            {
                                property.SetValue(element, null, null);
                            }
                            else
                            {
                                property.SetValue(element, rowElement[columnElement.ColumnName], null);
                            }
                        }
                    }
                }
                list.Add(element);
            }
            return list;
        }