把dataset对象转换成list集合方法

时间:2021-11-23 17:02:55
   public static List<T> GetList<T>(DataTable table) where T:new()
{
List<T> list = new List<T>();
//
T t = default(T);
PropertyInfo[] propertypes = null;
string tempName = string.Empty;
try
{
foreach (DataRow row in table.Rows)
{
//动态创建对象
t = Activator.CreateInstance<T>();
t = new T();
propertypes = t.GetType().GetProperties();
foreach (PropertyInfo pro in propertypes)
{
tempName = pro.Name;
if (table.Columns.Contains(tempName))
{
object value = row[tempName];
if (value != null && value != DBNull.Value && row[tempName].ToString() != null &&
!row[tempName].ToString().Trim().Equals(""))
{
if (tempName.Trim().ToLower().Equals("lastmodify"))
{
// pro.SetValue(t, ConvertHelper.ConvertToTimestamp(Convert.ToString(value)), null);
}
else
{
if (pro.PropertyType == typeof(System.Char) || pro.PropertyType == typeof(System.Nullable<System.Char>))
{
pro.SetValue(t, Convert.ToChar(value), null);
}
else
{
pro.SetValue(t, value, null);
} }
}
}
}
list.Add(t);
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return list;
}

1、  T t = default(T);  表示获得T类型

2、     t = Activator.CreateInstance<T>(); 根据类型创建对象

3、获得所有的属性

propertypes = t.GetType().GetProperties();

4、 pro.SetValue(t, value, null);设置相应对象的属性值