datatale和list转换

public static DataTable ToDataTable(IList list)
{
DataTable result = new DataTable();
if (list.Count > 0)
{
PropertyInfo[] propertys = list[0].GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
result.Columns.Add(pi.Name);
}

for (int i = 0; i < list.Count; i++)
{
ArrayList tempList = new ArrayList();
foreach (PropertyInfo pi in propertys)
{
object obj = pi.GetValue(list[i], null);
tempList.Add(obj);
}
object[] array = tempList.ToArray();
result.LoadDataRow(array, true);
}
}
return result;
}

public static List<T> DataTableToList<T>( DataTable dt)
{
var list = new List<T>();
Type t = typeof(T);
var plist = new List<PropertyInfo>(typeof(T).GetProperties());

foreach (DataRow item in dt.Rows)
{
T s = System.Activator.CreateInstance<T>();
for (int i = 0; i < dt.Columns.Count; i++)
{
PropertyInfo info = plist.Find(p => p.Name == dt.Columns[i].ColumnName);
if (info != null)
{
if (!Convert.IsDBNull(item[i]))
{
info.SetValue(s, item[i], null);
}
}
}
list.Add(s);
}
return list;
}

posted @ 2016-06-22 16:12  郭晓伟  阅读(173)  评论(0编辑  收藏  举报