#region DataTableToObjList
/// <summary>
/// DataTable数据转成Entity
/// </summary>
/// <typeparam name="T">Entity</typeparam>
/// <param name="ds">数据集</param>
/// <param name="tbName">表名</param>
/// <returns></returns>
public static List<T> DataTableToObjList<T>(DataTable dt) where T : new()
{
List<T> list = new List<T>();
PropertyInfo[] propinfos = null;
foreach (DataRow dr in dt.Rows)
{
T entity = new T();
//初始化propertyinfo
if (propinfos == null)
{
Type objtype = entity.GetType();
propinfos = objtype.GetProperties();
}
//填充entity类的属性
foreach (PropertyInfo propinfo in propinfos)
{
foreach (DataColumn dc in dt.Columns)
{
if (dc.ColumnName.ToUpper().Equals(propinfo.Name.ToUpper()))
{
string v = null;
v = dr[dc.ColumnName].ToString();
if (!String.IsNullOrEmpty(v))
{
if (propinfo.PropertyType.Equals(typeof(DateTime?)))
{
propinfo.SetValue(entity, (System.Nullable<DateTime>)DateTime.Parse(v), null);
}
else if (propinfo.PropertyType.Equals(typeof(System.Boolean?)))
{
propinfo.SetValue(entity, System.Boolean.Parse(v), null);
}
else if (propinfo.PropertyType.Equals(typeof(int?)))
{
propinfo.SetValue(entity, Convert.ToInt32(v), null);
}
else
{
propinfo.SetValue(entity, Convert.ChangeType(v, propinfo.PropertyType), null);
}
break;
}
}
}
}
list.Add(entity);
}
return list;
}
#endregion
只要做判断都是可以的:)