Как преобразовать список объектов в datatable и сохранить тип данных для значений.
public class Student { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } } List<Student> studentList = new List<Student> { new Student {Id = 1, Name = "John", Age = 12 }, new Student {Id = 2, Name = "Mary", Age = 11 }, new Student {Id = 3, Name = "Mike", Age = 13 } };
Extenteded method to convert list to datatable public class ListtoDataTableConverter { public DataTable ToDataTable<T>(List<T> items) { DataTable dataTable = new DataTable(typeof(T).Name); // Get all the properties PropertyInfo[] Props = typeof(T).GetProperties((BindingFlags.Public | BindingFlags.Instance)); foreach (PropertyInfo prop in Props) { // Setting column names as Property names dataTable.Columns.Add(prop.Name); } foreach (T item in items) { object values = new object[] { (Props.Length - 1)}; for (int i = 0; (i <= (Props.Length - 1)); i++) { // inserting property values to datatable rows values[i] = Props[i].GetValue(item, null); } dataTable.Rows.Add(values); } // put a breakpoint here and check datatable return dataTable; } }
Что я уже пробовал:
public class ListtoDataTableConverter { public DataTable ToDataTable<T>(List<T> items) { DataTable dataTable = new DataTable(typeof(T).Name); // Get all the properties PropertyInfo[] Props = typeof(T).GetProperties((BindingFlags.Public | BindingFlags.Instance)); foreach (PropertyInfo prop in Props) { // Setting column names as Property names dataTable.Columns.Add(prop.Name); } foreach (T item in items) { object values = new object[] { (Props.Length - 1)}; for (int i = 0; (i <= (Props.Length - 1)); i++) { // inserting property values to datatable rows values[i] = Props[i].GetValue(item, null); } dataTable.Rows.Add(values); } // put a breakpoint here and check datatable return dataTable; } }