/* This is a generic method that will convert any type of DataTable to a List
*
*
* Example : List<Student> studentDetails = new List<Student>();
* studentDetails = ConvertDataTable<Student>(dt);
*
* Warning : In this case the DataTable column's name and class property name
* should be the same otherwise this function will not work properly
*/
Ниже приведены две функции, в которых, если мы передаем DataTable и определенный пользователем класс. Затем он вернет список этого класса с данными DataTable.
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;
}
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())
{
//in case you have a enum/GUID datatype in your model
//We will check field's dataType, and convert the value in it.
if (pro.Name == column.ColumnName){
try
{
var convertedValue = GetValueByDataType(pro.PropertyType, dr[column.ColumnName]);
pro.SetValue(obj, convertedValue, null);
}
catch (Exception e)
{
//ex handle code
throw;
}
//pro.SetValue(obj, dr[column.ColumnName], null);
}
else
continue;
}
}
return obj;
}
Этот метод будет проверять тип данных поля, а также конвертировать DataTable значение в к этому типу данных.
private static object GetValueByDataType(Type propertyType, object o)
{
if (o.ToString() == "null")
{
return null;
}
if (propertyType == (typeof(Guid)) || propertyType == typeof(Guid?))
{
return Guid.Parse(o.ToString());
}
else if (propertyType == typeof(int) || propertyType.IsEnum)
{
return Convert.ToInt32(o);
}
else if (propertyType == typeof(decimal))
{
return Convert.ToDecimal(o);
}
else if (propertyType == typeof(long))
{
return Convert.ToInt64(o);
}
else if (propertyType == typeof(bool) || propertyType == typeof(bool?))
{
return Convert.ToBoolean(o);
}
else if (propertyType == typeof(DateTime) || propertyType == typeof(DateTime?))
{
return Convert.ToDateTime(o);
}
return o.ToString();
}
Для вызова предшествующего метода, используйте следующий синтаксис:
List<Student> studentDetails = new List<Student>();
studentDetails = ConvertDataTable<Student>(dt);
Изменение имя класса Student и значение дта на основе ваших требований.В этом случае имя столбца DataTable и имя свойства класса должны быть одинаковыми, иначе эта функция не будет работать должным образом.
Что вы пытаетесь выполнить с помощью списка, который вы не можете сделать с помощью DataRowCollection? – 2008-10-16 13:25:09