C#--List转DataTable(或DataSet)
/// <summary> /// List转DataTable /// </summary> /// <typeparam name="T"></typeparam> /// <param name="data"></param> /// <returns></returns> public static DataSet ListToDataTable<T>(List<T> data) { DataSet ds = new DataSet(); PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T)); DataTable dataTable = new DataTable(); for (int i = 0; i < properties.Count; i++) { PropertyDescriptor property = properties[i]; dataTable.Columns.Add(property.Name, Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType); } object[] values = new object[properties.Count]; foreach (T item in data) { for (int i = 0; i < values.Length; i++) { values[i] = properties[i].GetValue(item); } dataTable.Rows.Add(values); } ds.Tables.Add(dataTable); return ds; }