This article describes how to convert Data Table to List of Objects. In following code, you can simply convert DataTable to object type List in C#
Firstly, we create the Extension class (as MyExtensions).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | public static class MyExtensions { public static List<T> ToList<T>(this DataTable table) where T : class, new() { try { List<T> list = new List<T>(); foreach (var row in table.AsEnumerable()) { T obj = new T(); foreach (var prop in obj.GetType().GetProperties()) { try { PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name); propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null); } catch { continue; } } list.Add(obj); } return list; } catch { return null; } } } |
Then create a sample class for filling datatable to list ( I created Person class that Person has id, name, lastname and date )
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public class Person { int id; string firstName; string lastName; DateTime date; public int Id { get => id; set => id = value; } public string FirstName { get => firstName; set => firstName = value; } public string LastName { get => lastName; set => lastName = value; } public DateTime Date { get => date; set => date = value; } } |
After adding Person class and MyExtensions, we can write main code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | class Program { static void Main(string[] args) { //Sample data Console.Write("\n Write DataTable Objects \n"); DataTable dt = new DataTable("Test"); dt.Columns.Add("ID", typeof(int)); dt.Columns.Add("FirstName", typeof(string)); dt.Columns.Add("LastName", typeof(string)); dt.Columns.Add("Date", typeof(DateTime)); dt.Rows.Add(1, "Marc", "Sun", "19.03.1999"); dt.Rows.Add(2, "Mike", "Mon", "20.08.2000"); dt.Rows.Add(3, "Bob", "Tue", "11.11.2011"); dt.Rows.Add(4, "Eric", "Red", DateTime.Now); //listing datatable foreach (DataRow dr in dt.Rows) { Console.WriteLine("ID : {0}\tFirst Name : {1} \t Last Name : {2} \t Date : {3}", dr[0], dr[1], dr[2], dr[3]); } List<Person> myList = dt.ToList<Person>(); /*Convert to List using by Extetion method*/ //listing list Console.Write("\n Write List Objects \n"); foreach (var item in myList) { Console.WriteLine("ID : {0}\tFirst Name : {1} \t Last Name : {2} \t Date : {3}", item.Id, item.FirstName, item.LastName, item.Date); } Console.ReadLine(); } } |
Output: