private static DataTable ListToDataTable(IList list)
{
DataTable result = new DataTable();
if (list.Count > 0)
{
PropertyInfo[] propertys = list[0].GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
//获取类型
Type colType = pi.PropertyType;
//当类型为Nullable<>时
if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
{
colType = colType.GetGenericArguments()[0];
}
result.Columns.Add(pi.Name, colType);
}
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;
}
datatable转换成List
public static List<T> TableToList<T>(T obj, DataTable tt)
{
System.Type type = obj.GetType();
List<T> list = new List<T>();
for (int i = 0; i < tt.Rows.Count; i++)
{
T item = (T)Activator.CreateInstance(type);
object value;
foreach (DataColumn c in tt.Columns)
{
value = tt.Rows[i][c];
if (value != System.DBNull.Value)
{
type.GetProperty(c.ColumnName).SetValue(item, tt.Rows[i][c], null);
}
}
list.Add(item);
}
return list;
}