Code review for converting datatable to list

  • Thread starter Thread starter Sudip_inn
  • Start date Start date
S

Sudip_inn

Guest
see the code

public static List<T> ConvertToDataTable<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;
}

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)
pro.SetValue(obj, dr[column.ColumnName], null);
else
continue;
}
}
return obj;
}

calling this way

var JoinResult2 = (from p in dt.AsEnumerable().AsParallel() /*.AsOrdered()*/
join t in dtTax.AsEnumerable().AsParallel() /*.AsOrdered()*/
on p.Field<int>("Tax Id") equals t.Field<int>("Tax Id") into pj
from r in pj.DefaultIfEmpty()
select new
{
ProductName = p.Field<string>("Product Name"),
BrandName = p.Field<string>("Brand Name"),
ProductCategory = r == null ? "" : r.Field<string>("Product Category"),
TaxCharge = r == null ? 0 : r.Field<int>("Charge")
}).ToList().ToDataTable();
List<MyData> mc = new List<MyData>();
mc = Extension.ConvertToDataTable<MyData>(JoinResult2);

dataGridView1.DataSource = mc;

tell me when there will be huge data in datatable then does the above function ConvertToDataTable() will work faster?

if not then what will be best approach ?

how to map if my property name & datatable column name would be different ?

Continue reading...
 
Back
Top