近期写项目,使用小型数据库,不值当的使用框架,但是习惯了使用封装好的list对象,突然使用datatable 很不习惯,感觉太原始了,
以下是我写的对于datatable与list的互转,共同学习。
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
namespace CommonUtil
{
public class ConverterUtil
{
/// <summary>
/// 将datatabble类型数据转换成list对象列表
/// </summary>
public static List<T> ConvertDataTableToList<T>(DataTable dt) where T : class ,new()
{
if (dt == null || dt.Rows.Count == 0)
{
return null;
}
var modelList = new List<T>();
foreach (DataRow dr in dt.Rows)
{
//T model = (T)Activator.CreateInstance(typeof(T));
var model = new T();
for (int i = 0; i < dr.Table.Columns.Count; i++)
{
PropertyInfo propertyInfo = model.GetType().GetProperty(dr.Table.Columns[i].ColumnName);
if (propertyInfo != null && dr[i] != DBNull.Value)
{
object value = dr[i];
if (propertyInfo.PropertyType == typeof(double))
{
value = double.Parse(dr[i].ToString());
}
else if (propertyInfo.PropertyType == typeof(int))
{
value = int.Parse(dr[i].ToString());
}
else if (propertyInfo.PropertyType == typeof(float))
{
value = float.Parse(dr[i].ToString());
}
else if (propertyInfo.PropertyType == typeof(DateTime))
{
value = DateTime.Parse(dr[i].ToString());
}
else
{
value = dr[i].ToString();
}
propertyInfo.SetValue(model, value, null);
}
}
modelList.Add(model);
}
return modelList;
}
/// <summary>
/// 将datatabble类型数据转换成list对象列表
/// </summary>
public static DataTable ConvertListToDataTable<T>(List<T> list)
{
if (list == null || list.Count == 0)
{
return null;
}
var table = new DataTable();
var type = typeof(T);
foreach (var pro in type.GetProperties())
{
table.Columns.Add(new DataColumn(pro.Name));
}
var num = list.Count;
for (var i = 0; i < num; i++)
{
var row = table.NewRow();
foreach (var pro in type.GetProperties())
{
row[pro.Name] = pro.GetValue(list[i], null);
}
table.Rows.Add(row);
}
return table;
}
}
}