datatable转List<T>集合
/// <summary>
/// datatable表转list集合
/// </summary>
/// <typeparam name="T">实体类</typeparam>
/// <param name="dt">datatable表</param>
/// <param name="rowStart">表的第几行开始计算</param>
/// <returns>集合List</returns>
private static List<T> DataTableToList<T>(System.Data.DataTable dt, int rowStart) where T : new()
{
List<T> lists = null;
if (dt.Rows.Count > 0)
{
lists = new List<T>();//定义集合
string tempName = string.Empty;
for (int i = rowStart; i < dt.Rows.Count; i++)
{
DataRow myRow = dt.Rows[i];//获取当前行
T t = new T();
#region 反射入List
Type type = t.GetType();
foreach (var pi in type.GetProperties())//遍历公共属性
{
tempName = pi.Name;
if (dt.Columns.Contains(tempName))
{
if (!pi.CanWrite) continue;//该属性不可写,直接跳出
if (!pi.PropertyType.IsGenericType)//对属性中有DateTime进行区分对待
{
if (pi.Name == "Guid")//对属性为Guid进行特别处理
{
Guid guid = Guid.Empty;
if (!Guid.TryParse(myRow[tempName].ToString(), out guid)) { guid = Guid.NewGuid(); }
pi.SetValue(t, Convert.ChangeType(guid, pi.PropertyType), null);
}
else
{
pi.SetValue(t, Convert.ChangeType(myRow[tempName], pi.PropertyType), null);
}
}
else
{
pi.SetValue(t, Convert.ChangeType(myRow[tempName], Nullable.GetUnderlyingType(pi.PropertyType)), null);
}
}
#endregion
}
lists.Add(t);
}
}
return lists;
}
}