ASP.NET - List To DataTable 發表於 2017-12-21 | 更新於 2019-01-09 | 分類於 ASP.NET 123456789101112131415161718192021public DataTable ConvertToDataTable<T>(IList<T> data){ PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T)); DataTable table = new DataTable(); foreach ( PropertyDescriptor prop in properties ) { table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType); } foreach ( T item in data ) { DataRow row = table.NewRow(); foreach ( PropertyDescriptor prop in properties ) { row[prop.Name] = prop.GetValue(item) ?? DBNull.Value; } table.Rows.Add(row); } return table;}