public static class DBHelper<T>
{
public static void ConvertDataRowToModel(T modelObj, DataRow dataRow)
{
var properties = from prop in modelObj.GetType().GetProperties()
select prop;
foreach (var property in properties)
{
dynamic propertyValue = null;
foreach (DataColumn col in dataRow.Table.Columns)
{
if (property.Name.ToUpper().Equals(col.ColumnName.ToString().ToUpper()))
{
propertyValue = dataRow[col.ColumnName] != DBNull.Value ? dataRow[col.ColumnName] : null;
break;
}
}
if (propertyValue != null)
{
var propertyType = property.PropertyType.FullName;
if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
propertyType = property.PropertyType.GetGenericArguments()[0].FullName;
}
switch (propertyType)
{
case "System.Int32":
{
property.SetValue(modelObj, Convert.ToInt32(propertyValue), null);
break;
}
case "System.Nullable[System.Int32]":
{
property.SetValue(modelObj, Convert.ToInt32(propertyValue), null);
break;
}
case "System.Int64":
{
property.SetValue(modelObj, Convert.ToInt64(propertyValue), null);
break;
}
case "System.Boolean":
{
property.SetValue(modelObj, Convert.ToBoolean(Convert.ToInt16(propertyValue)), null);
break;
}
case "System.String":
{
var val = WebUtility.HtmlDecode(Convert.ToString(propertyValue));
property.SetValue(modelObj, val, null);
break;
}
case "System.DateTime":
{
property.SetValue(modelObj, Convert.ToDateTime(propertyValue), null);
break;
}
case "System.Decimal":
{
property.SetValue(modelObj, Math.Round(Convert.ToDecimal(propertyValue), 2), null);
break;
}
case "System.Double":
{
property.SetValue(modelObj, Math.Round(Convert.ToDouble(propertyValue), 2), null);
break;
}
case "System.Byte[]":
{
property.SetValue(modelObj, (Byte[])(propertyValue), null);
break;
}
default:
{
Type t = Enum.GetUnderlyingType(property.PropertyType);
switch (t.FullName)
{
case "System.Int16":
{
property.SetValue(modelObj, Convert.ToInt16(propertyValue), null);
break;
}
case "System.Int32":
{
property.SetValue(modelObj, Convert.ToInt32(propertyValue), null);
break;
}
}
break;
}
}
}
}
}
public static List<T> ConvertDataTableToModelList(DataTable dataTable)
{
List<T> modelList = new List<T>();
foreach (DataRow dataRow in dataTable.Rows)
{ var ob = Activator.CreateInstance<T>();
ConvertDataRowToModel(ob, dataRow);
modelList.Add(ob);
}
return modelList;
}
}
Над классом есть метод generi c для преобразования таблицы данных в список. механизм вызова: Lstsample lstsample == DBHelper.ConvertDataTableToModelList (datasetsample.Tables [0]);