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

public IList<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;
        }
原文地址:https://www.cnblogs.com/jeffrey77/p/2598086.html