首页 > 代码库 > C# List<T> To DataTable

C# List<T> To DataTable

 1 public DataTable ConvertToDataTable<T>(IList<T> data)
 2     {
 3         PropertyDescriptorCollection properties =
 4            TypeDescriptor.GetProperties(typeof(T));
 5         DataTable table = new DataTable();
 6         foreach (PropertyDescriptor prop in properties)
 7             table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
 8         foreach (T item in data)
 9         {
10             DataRow row = table.NewRow();
11             foreach (PropertyDescriptor prop in properties)
12                 row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
13             table.Rows.Add(row);
14         }
15         return table;
16 
17     }