C# DataTable to List Convert

public static List DataTableToList(this DataTable table) where T : class, new()

        {
           try
            {
                List list = new List();
                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;
            }
        }

Reference: http://littleprograming.blogspot.com/2014/11/c-datatable-to-list-convert.html

Comments

Popular posts from this blog

How to use DbFunctions.TruncateTime

Provision AWS EC2 Instance and RDS with Terraform, and Deploy Spring Boot App to EC2 Instance via GitHub Action Pipeline

Microsoft Access Connectivity from C#