C#中DataTable和List互转
1. DataTable转List
public class DtToList<T> where T : new()
{
public static List<T> ConvertToModel(DataTable dt)
{
List<T> ts = new List<T>();
Type type = typeof(T);
string tempName = "";
foreach (DataRow dr in dt.Rows)
{
T t = new T();
PropertyInfo[] propertys = t.GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
tempName = pi.Name;
if (dt.Columns.Contains(tempName))
{
if (!pi.CanWrite) continue;
object value = dr[tempName];
if (value != DBNull.Value)
pi.SetValue(t, value, null);
}
}
ts.Add(t);
}
return ts;
}
}
2. List转DataTable
public DataTable ListToDt<T>(IEnumerable<T> collection)
{
var props = typeof(T).GetProperties();
var dt = new DataTable();
dt.Columns.AddRange(props.Select(p => new
DataColumn(p.Name, p.PropertyType)).ToArray());
if (collection.Count() > 0)
{
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;
}
3. 使用
List<CustomerContact> list = GetCustomerContact();
DataTable dt = ListToDt<CustomerContact>(list);
foreach (DataRow mDr in dt.Rows)
{
foreach (DataColumn mDc in dt.Columns)
{
}
}
List<CustomerContact> list2 = DtToList<CustomerContact>.ConvertToModel(dt);