给DataTable添加列
string sql = "select * from cgpmb order by code";
DataTable dt = Bobole.Data.OracleDataRegester.GetListBySql(sql).Tables[];
dt.Columns.Add("PCode", typeof(string)); //假如数据库查询出来的DataTable没有你想要的列 Remove("")可以删除列
for (int i = ; i < dt.Rows.Count; i++)
{
try
{
dt.Rows[i]["PCode"] = dt.Rows[i]["Code"].ToString().Remove(dt.Rows[i]["Code"].ToString().Length - , );
}
catch (Exception)
{
dt.Rows[i]["PCode"] = "";
}
}
将DataTable转化为list泛型集合
public static List<T> TableToList<T>(DataTable dt, bool isStoreDB = true)
{
List<T> list = new List<T>();
Type type = typeof(T);
//List<string> listColums = new List<string>();
PropertyInfo[] pArray = type.GetProperties(); //集合属性数组
foreach (DataRow row in dt.Rows)
{
T entity = Activator.CreateInstance<T>(); //新建对象实例
foreach (PropertyInfo p in pArray)
{
if (!dt.Columns.Contains(p.Name) || row[p.Name] == null || row[p.Name] == DBNull.Value)
{
continue; //DataTable列中不存在集合属性或者字段内容为空则,跳出循环,进行下个循环
}
if (isStoreDB && p.PropertyType == typeof(DateTime) && Convert.ToDateTime(row[p.Name]) < Convert.ToDateTime("1753-01-01"))
{
continue;
}
try
{
var obj = Convert.ChangeType(row[p.Name], p.PropertyType);//类型强转,将table字段类型转为集合字段类型
p.SetValue(entity, obj, null);
}
catch (Exception)
{
// throw;
}
}
list.Add(entity);
}
return list;
}
将list泛型集合转化为DataTable
/// <summary>
/// 转化一个DataTable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
private static System.Data.DataTable ToDataTable<T>(IEnumerable<T> list)
{
//创建属性的集合
List<PropertyInfo> pList = new List<PropertyInfo>();
//获得反射的入口
Type type = typeof(T);
System.Data.DataTable dt = new System.Data.DataTable();
//把所有的public属性加入到集合 并添加DataTable的列
Array.ForEach<PropertyInfo>(type.GetProperties(), p => { pList.Add(p); dt.Columns.Add(p.Name, p.PropertyType); });
foreach (var item in list)
{
//创建一个DataRow实例
DataRow row = dt.NewRow();
//给row 赋值
pList.ForEach(p => row[p.Name] = p.GetValue(item, null));
//加入到DataTable
dt.Rows.Add(row);
}
return dt;
}