数据处理随笔
// List集合转DataTable
public static DataTable ListToDataTable<T>(IEnumerable<T> collection)
{
if (collection == null)
throw new ArgumentNullException();
PropertyInfo[] props = typeof(T).GetProperties();
DataTable dt = new DataTable();
dt.Columns.AddRange(props.Select(p => new DataColumn(p.Name, p.PropertyType)).ToArray());
if (collection.Any())
{
for (int i = 0; i < collection.Count(); i++)
{
ArrayList tempList = new ArrayList();
foreach (PropertyInfo pi in props)
{
object obj = pi.GetValue(collection.ElementAt(i), null);
tempList.Add(obj);
}
object[] array = tempList.ToArray();
dt.LoadDataRow(array, true);
}
}
return dt;
}
// DataTable 转 List
public static List<T> DataTableToList<T>(DataTable dt) where T : new()
{
List<T> result = new List<T>();
foreach (DataRow dr in dt.Rows)
{
T item = new T();
PropertyInfo[] props = item.GetType().GetProperties();
foreach (PropertyInfo pi in props)
{
string tempName = pi.Name;
if (dt.Columns.Contains(tempName))
{
if (pi.CanWrite == false)
continue;
object value = dr[tempName];
if (value != DBNull.Value)
pi.SetValue(item, value, null);
}
}
result.Add(item);
}
return result;
}