DataTable和List集合互转

时间:2022-05-08 09:42:37
 /// <summary>
/// 将集合转换成DataTable
/// </summary>
/// <param name="list">集合</param>
/// <returns></returns>
public static DataTable ToDataTable(IList list)
{
DataTable result = new DataTable();
if (list.Count > )
{
PropertyInfo[] propertys = list[].GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
result.Columns.Add(pi.Name, pi.PropertyType);
}
for (int i = ; 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;
} /// <summary>
/// 讲DataTable转换成集合
/// </summary>
/// <param name="dt">数据表</param>
/// <returns></returns>
public static IList<CarNum> ToList(DataTable dt)
{
// 定义集合
IList<CarNum> ts = new List<CarNum>(); // 获得此模型的类型
Type type = typeof(CarNum); string tempName = ""; foreach (DataRow dr in dt.Rows)
{
CarNum t = new CarNum(); // 获得此模型的公共属性
PropertyInfo[] propertys = t.GetType().GetProperties(); foreach (PropertyInfo pi in propertys)
{
tempName = pi.Name; // 检查DataTable是否包含此列
if (dt.Columns.Contains(tempName))
{
// 判断此属性是否有Setter
if (!pi.CanWrite) continue; object value = dr[tempName];
if (value != DBNull.Value)
pi.SetValue(t, value, null);
}
} ts.Add(t);
} return ts; }