Convert DataTable from list and Vice Versa..

Convert DataTable


First Approach :-

public static DataTable ToDataTable<T>(List<T> items)
{
        DataTable dataTable = new DataTable(typeof(T).Name);

        //Get all the properties
        PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (PropertyInfo prop in Props)
        {
            //Defining type of data column gives proper data table 
    var type = (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType);
            //Setting column names as Property names
            dataTable.Columns.Add(prop.Name, type);
        }
        foreach (T item in items)
        {
           var values = new object[Props.Length];
           for (int i = 0; i < Props.Length; i++)
           {
                //inserting property values to datatable rows
                values[i] = Props[i].GetValue(item, null);
           }
           dataTable.Rows.Add(values);
      }
      //put a breakpoint here and check datatable
      return dataTable;
}
Second Approach :-

public DataTable ConvertToDataTable<T>(IList<T> data)
{
    PropertyDescriptorCollection properties =
    TypeDescriptor.GetProperties(typeof(T));
    DataTable table = new DataTable();
    foreach (PropertyDescriptor prop in properties)
        table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
    foreach (T item in data)
    {
        DataRow row = table.NewRow();
        foreach (PropertyDescriptor prop in properties)
            row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
        table.Rows.Add(row);
    }
    return table;
}
Note : what I preferred is the second Approach


DataTable to List



public class ConvertDataTableToList
{
    /// <summary>
    /// To convert data table to list
    /// of class objects
    /// </summary>
    /// <typeparam name="T">Class Name to Convert</typeparam>
    /// <param name="dt">Data table to convert</param>
    /// <returns></returns>
    public static List<T> ConvertDataTable<T>(DataTable dt)
    {
        List<T> data = new List<T>();
        foreach (DataRow row in dt.Rows)
        {
            T item = GetItem<T>(row);
            data.Add(item);
        }
        return data;
    }

    /// <summary>
    /// Mapping data row to class object
    /// </summary>
    /// <typeparam name="T">Class Name</typeparam>
    /// <param name="dr">Data row</param>
    /// <returns></returns>
    private static T GetItem<T>(DataRow dr)
    {
        Type temp = typeof(T);
        T obj = Activator.CreateInstance<T>();

        foreach (DataColumn column in dr.Table.Columns)
        {
            foreach (PropertyInfo pro in temp.GetProperties())
            {
                if (pro.Name == column.ColumnName)
                {
                    if (pro.PropertyType == typeof(Int64))
                    {
                        var valueToset = dr[column.ColumnName] == DBNull.Value ? 0 : Convert.ToInt64(dr[column.ColumnName]);
                        pro.SetValue(obj, valueToset, null);
                    }
                    else if (pro.PropertyType == typeof(Nullable<Decimal>))
                    {
                        var sa = dr[column.ColumnName].ToString();
                        try
                        {

                            var valueToset = dr[column.ColumnName] == DBNull.Value || dr[column.ColumnName].ToString() == null ? 0 : Convert.ToDecimal(dr[column.ColumnName].ToString().Replace(",", ""));
                            pro.SetValue(obj, valueToset, null);
                        }
                        catch
                        {
                            if (sa == "")
                            {
                                pro.SetValue(obj, Convert.ToDecimal(0.0), null);
                            }
                            else
                                throw new Exception("Invalid excel data please verify.");
                        }
                    }
                    else if (pro.PropertyType == typeof(Nullable<bool>))
                    {
                        var valueToset = dr[column.ColumnName] == DBNull.Value ? false : Convert.ToBoolean(dr[column.ColumnName].ToString());
                        pro.SetValue(obj, valueToset, null);
                    }
                    else if (pro.PropertyType == typeof(string))
                    {
                        var valueToset = dr[column.ColumnName] == DBNull.Value ? "" : dr[column.ColumnName].ToString();
                        pro.SetValue(obj, valueToset, null);
                    }
                    else if (pro.PropertyType == typeof(Nullable<DateTime>))
                    {
                        var yearstart = DateTime.Now.Year;
                        //var valueToset = dr[column.ColumnName] == DBNull.Value ? DateTime.Now : Convert.ToDateTime(dr[column.ColumnName].ToString());
                        var valueToset = dr[column.ColumnName] == DBNull.Value ? new DateTime(yearstart,1,1) : Convert.ToDateTime(dr[column.ColumnName].ToString());
                        pro.SetValue(obj, valueToset, null);
                    }
                    else
                    {
                        pro.SetValue(obj, dr[column.ColumnName], null);
                    }
                }
                else
                    continue;
            }
        }
        return obj;
    }
}


Final Words:

This is simple if we know otherwise it will create a to difficulty things.

Please feel free to contact if u have any doubts and suggestions.

Comments

Popular Posts