Convert DataTable to List

I have learned the previous article< Convert list < T > to DataTable>

In that article, we will learn to reverse and convert datatable to list < T >. This method is widely used. In many cases, the data read from the data is a DataSet or a DataTable. You need to convert them to list < T > and then to json.

Next, Insus.NET writes an extension method:


 public static List<T> ToList<T>(this DataTable dt)
            var dataColumn = dt.Columns.Cast<DataColumn>().Select(c => c.ColumnName).ToList();

            var properties = typeof(T).GetProperties();
            string columnName = string.Empty;

            return dt.AsEnumerable().Select(row =>
                var t = Activator.CreateInstance<T>();
                foreach (var p in properties)
                    columnName = p.Name;
                    if (dataColumn.Contains(columnName))
                        if (!p.CanWrite)

                        object value = row[columnName];
                        Type type = p.PropertyType;

                        if (value != DBNull.Value)
                            p.SetValue(t, Convert.ChangeType(value, type), null);
                return t;
Source Code


Next, create a DataTable manually and add some data rows. Object is the object of the previous article:


 class Ba
        public void ConvertDataTableToListToTestDemo()
            DataTable dt = new DataTable();
            dt.Columns.Add("ID", typeof(int));
            dt.Columns.Add("Account", typeof(string));
            dt.Columns.Add("Email", typeof(string));

            dt.Rows.Add(1, "A0001", "");
            dt.Rows.Add(2, "A0002", "");
            dt.Rows.Add(3, "A0003", "");

            List<Ay> ays = dt.ToList<Ay>();

            ays.ForEach(delegate (Ay ay)
Source Code


The red box in the figure above is the 23 line code, which is the core code of this article. Convert DataTable to list < T >.


Test the following code on the console:

Tags: C# JSON

Posted on Mon, 18 May 2020 08:54:16 -0700 by SauloA