验证中...
DataTable转换成为泛型集合,泛型集合转换成DataTable
Raw Copy
开发的时候往往离不开对数据库的操作,有的时候数据库返回的是一个DataTable对象,这个时候我们需要将DataTable转换成为泛型集合对象来操作
List<T> To DataTable
public static List<T> ConvertToListT<T>(DataTable dt) where T:new()
{
if(dt==null)
{
return null;
}
if(dt.Rows.Count<=0)
{
return null;
}
List<T> result = new Liist<T>();
Type type= typeof(T);
PropertyInfo[] propertyInfos = type.GetProperties();
List<DataColumn> listColumns = dt.Columns.Cast<DataColumn>().ToList();
T t;
foreach(DataRow dr in dt.Rows)
{
t = new T();
foreach(PropertyInfo propertyInfo in propertyInfos )
{
try
{
DataColumn dColumns = listColumns.Find(name=>name.ToString().ToUpper()==propertyInfo.Name.ToUpper());
if(dcolumns!=null)
{
propertyInfo.SetValue(t,dr[propertyInfo.Name],null);
}
}
catch(Exception ex)
{
throw new Exception(ex.Message);
}
}
result.Add(t);
}
return result;
}
DataTable To List<T>
public static DataTable ListToDataTable<T>(List<T> entities)
{
Type type = typeof(T);
PropertyInfo[] propertyInfos = type.GetProperties();
DataTable dt = new DataTable(type.Name);
foreach(var item in propertyInfos)
{
dt.Columns.Add(new DataColumn(item.Name){DataType = item.PropertyType});
}
foreach(var item in entities)
{
DataRow dr = dt.NewRow();
foreach(var property in propertyInfos)
{
dr[property.Name] = property.GetValue(item);
}
dt.Rows.Add(dr);
}
return dt;
}

Comment list( 0 )

You need to Sign in for post a comment

Help Search

183227_9af5e6a8_1826025 111910_4d91f001_1826025