Translate

> | | > DataTable to C# Class List Converter

DataTable to C# Class List Converter

Posted on Monday, December 25, 2017 | No Comments

  public static List<T> DataTableToList<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);

                            var value = row[prop.Name];
                            if (value == DBNull.Value)
                            {
                                value = null;
                            }
                            //propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null);
                            prop.SetValue(obj, value, null);
                        }
                        catch
                        {
                            continue;
                        }
                    }

                    list.Add(obj);
                }

                return list;
            }
            catch
            {
                return null;
            }
        }

Leave a Reply

Powered by Blogger.