Click here to Skip to main content
15,887,267 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
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;
    }
}


What I have tried:

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;
    }
}
Posted
Updated 14-Sep-17 9:28am

1 solution

 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900