I need to optimize this code block below, this method converts a Datatable object to the Object that I am passing by parameter, in another words, this serializes the object, however I have to run this block 1 million times when reading data from the database, so this is the bottleneck of my application.
Obs: All my objects that I use in this method have a property "Id" which is the PrimaryKey of the table, but the name of the primary key in the database is different, so that's why I have that "if command" asking the name of the primary key.
How can I optimize this code below?
public static List<T> BindDataList<T>(DataTable dt, string primaryKey)
{
// Get all columns' name
var columns = (from DataColumn dc in dt.Columns select dc.ColumnName);
var properties = typeof(T).GetProperties().ToList();
var lst = new List<T>();
foreach (DataRow dr in dt.Rows)
{
// Create object
var ob = Activator.CreateInstance<T>();
// Get all properties
properties.ForEach(propertyInfo =>
{
if (columns.Any(s => s.Equals(propertyInfo.Name, StringComparison.OrdinalIgnoreCase)))
{
// Fill the data into the property
if (!(dr[propertyInfo.Name] is DBNull))
propertyInfo.SetValue(ob, dr[propertyInfo.Name]);
}
else
{
if (propertyInfo.Name.ToUpper().Equals("ID"))
{
// Fill the data into the property
if (!(dr[primaryKey] is DBNull))
{
propertyInfo.SetValue(ob, dr[primaryKey].SafeToInt());
}
}
}
});
lst.Add(ob);
}
return lst;
}
DataTable
coming from? If it's coming from a database as the question implies, you might be far better off pulling the data into your data objects directly, either through anIDataReader
or even better, an ORM. \$\endgroup\$