HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMajor

Converting DataTable to List of class

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
datatableconvertinglistclass

Problem

I am using ExcelDataReader to import an Excel file to a dataset.

Example Excel table:

//ID     Name     Display Order    Active
//1      John          1             1


ID, DisplayOrder and Active columns are read as double, so I have to convert them to long, int and bool types respectively. I need to create a list of type Category from the DataTable of the DataSet.

Will this code perform well? Any suggestions for a faster conversion of DataTable to List of class?

var list = result.Tables["Categories"].AsEnumerable()
.Skip(1)
.Select(dr =>
        new Category
            {
                Id = Convert.ToInt64(dr.Field("ID")),
                Name = dr.Field("Name"),
                DisplayOrder = Convert.ToInt32(dr.Field("Display Order")),
                IsActive= dr.Field("Active") == 1 ? true : false
            }
        ).ToList();

Solution

I created an extension method for DataTable to convert them into a List

public static class Helper
{
    /// 
    /// Converts a DataTable to a list with generic objects
    /// 
    /// Generic object
    /// DataTable
    /// List with generic objects
    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;
        }
    }
}


Example:

DataTable dtTable = GetEmployeeDataTable();
List employeeList = dtTable.DataTableToList();

Code Snippets

public static class Helper
{
    /// <summary>
    /// Converts a DataTable to a list with generic objects
    /// </summary>
    /// <typeparam name="T">Generic object</typeparam>
    /// <param name="table">DataTable</param>
    /// <returns>List with generic objects</returns>
    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);
                        propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null);
                    }
                    catch
                    {
                        continue;
                    }
                }

                list.Add(obj);
            }

            return list;
        }
        catch
        {
            return null;
        }
    }
}
DataTable dtTable = GetEmployeeDataTable();
List<Employee> employeeList = dtTable.DataTableToList<Employee>();

Context

StackExchange Code Review Q#30714, answer score: 41

Revisions (0)

No revisions yet.