备忘 C# 转化
/// 根据dataTabel 得到实体对应的实体列表
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="table"></param>
/// <returns></returns>
public static List<T> DataTabToList<T>(DataTable table) where T : class, new()
{
List<T> ls = new List<T>();
if (table==null)
{
return ls;
}
if (table.Columns.Count==0)
{
return ls;
}
//1. 获取公共属性数组
var props = typeof(T).GetProperties();
#region 按照每行遍历 但这样 每行的每列都要再重新遍历
//2. 遍历datatable的所有行 每一行就是一个实体数据
//foreach (DataRow row in table.Rows)
//{
// T entity = new T();
// //根据反射获取共有属性
// foreach (DataColumn col in table.Columns)
// {
// foreach (PropertyInfo prop in props)
// {
// var objs = prop.GetCustomAttributes(typeof(DescriptionAttribute), false);
// if (objs != null && objs.Length > 0)
// {
// string curDescr = ((DescriptionAttribute)objs[0]).Description;
// if (curDescr == col.ColumnName)
// {
// //找到属性列 给对象赋值
// prop.SetValue(entity, Convert.ChangeType(row[col],prop.PropertyType),null);
// break;
// }
// }
// }
// }
// ls.Add(entity);
//}
#endregion
#region 如果按照每列去遍历,是否会快点呢
bool firstColFlag = true;
foreach (DataColumn column in table.Columns)
{
int idx = 0;
PropertyInfo curPorp = null;
foreach (PropertyInfo itemProp in props)
{
// 判断属性上的标签是否和table中的列表中字段是否一致
var obj = itemProp.GetCustomAttribute(typeof(DescriptionAttribute));
if (obj != null)
{
string curAttri = ((DescriptionAttribute)obj).Description;
if (curAttri == column.ColumnName)
{
curPorp = itemProp;
break;
}
}
}
if (curPorp == null)
{
continue;
}
foreach (DataRow row in table.Rows)
{
T entity = default(T);
if (firstColFlag)
{
entity = new T();
}
else
{
entity = ls[idx];
}
//根据公共属性数组添加设置到
try
{
curPorp.SetValue(entity, Convert.ChangeType(row[column], curPorp.PropertyType), null);
}
catch (Exception ex)
{
Console.WriteLine("给属性赋值失败!ex:{0}",ex.ToString());
continue;
}
//只有第一列需要添加到列表中
if (firstColFlag)
{
ls.Add(entity);
}
idx++;
}
firstColFlag = false;
}
#endregion
return ls;
}```