Convert DataTable to List

Convert DataTable to List in Asp.net MVC

Dynamic function that convert DataTable to List

just pass data table to the function you will the required List



public List<T> DataTableToList<T>(DataTable dataTable) where T : class, new()
        {
            try
            {
                List<T> list = new List<T>();

                for (int i = 0; i < dataTable.Rows.Count; i++)
                {
                    var row = dataTable.Rows[i];

                    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;
            }
     }

Post a Comment

0 Comments