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

C# List<T>转为 DataTable

 1 // remove "this" if not on C# 3.0 / .NET 3.5 2         public static System.Data.DataTable ConvertToDatatable<T>(this IList<T> data) { 3             System.ComponentModel.PropertyDescriptorCollection props = 4                 System.ComponentModel.TypeDescriptor.GetProperties(typeof(T)); 5             System.Data.DataTable table = new System.Data.DataTable(); 6             for (int i = 0; i < props.Count; i++) { 7                 System.ComponentModel.PropertyDescriptor prop = props[i]; 8                 table.Columns.Add(prop.Name, prop.PropertyType); 9             }10             object[] values = new object[props.Count];11             foreach (T item in data) {12                 for (int i = 0; i < values.Length; i++) {13                     values[i] = props[i].GetValue(item);14                 }15                 table.Rows.Add(values);16             }17             return table;18         }

 

C# List<T>转为 DataTable