实体类Employee:
public class Employee
{
public int EId { get; set; }
public string EName { get; set; }
public bool ESex { get; set; }
}
实体类Department:
public class Department
{
public int DId { get; set; }
public string DName { get; set; }
}
目标:使用一个方法,能将DataTable中的Employee、Department数据,转换为Employee、Department集合。
{
class Program
{
private static DataTable employeeDT = new DataTable();
private static DataTable departmentDT = new DataTable();
static void Main(string[] args)
{
InitTable();
List<Employee> eList = GetEntityFromDataTable<Employee>(employeeDT);
foreach (Employee e in eList)
{
Console.WriteLine("编号:{0} 部门:{1} 男:{2}",e.EId,e.EName,e.ESex);
}
List<Department> dList = GetEntityFromDataTable<Department>(departmentDT);
foreach (Department d in dList)
{
Console.WriteLine("编号:{0} 部门{1}", d.DId, d.DName);
}
Console.ReadKey();
}
/// <summary>
/// 初始化 员工、部门表的内容
/// </summary>
public static void InitTable()
{
employeeDT.Columns.Add("Eid",typeof(Int32));
employeeDT.Columns.Add("EName",typeof(string));
employeeDT.Columns.Add("ESex",typeof(bool));
DataRow dRow = employeeDT.NewRow();
dRow["Eid"] = 1;
dRow["EName"] = "小张";
dRow["ESex"] = true; //男
employeeDT.Rows.Add(dRow);
employeeDT.Rows.Add(new object[] {2,"小王",false});
employeeDT.Rows.Add(new object[] { 3, "小李",true });
departmentDT.Columns.Add("DId",typeof(Int32));
departmentDT.Columns.Add("DName",typeof(string));
departmentDT.Rows.Add(new object[] { 1, "硬件组" });
departmentDT.Rows.Add(new object[] { 2, "软件组" });
}
//public static List<Employee> GetEntityFromDataTable(DataTable sourceDT)
//{
// List<Employee> list = new List<Employee>();
// foreach (DataRow dRow in sourceDT.Rows)
// {
// Employee e = new Employee();
// e.EId = Convert.ToInt32(dRow["EId"]);
// e.EName = dRow["EName"].ToString();
// list.Add(e);
// }
// return list;
//}
/// <summary>
/// 将DataTable转为实体对象
/// </summary>
/// <typeparam name="T">目标类型</typeparam>
/// <param name="sourceDT">原DT</param>
/// <returns>转换后的实体列表</returns>
public static List<T> GetEntityFromDataTable<T>(DataTable sourceDT) where T:class
{
List<T> list = new List<T>();
// 获取需要转换的目标类型
Type type = typeof(T);
foreach (DataRow dRow in sourceDT.Rows)
{
// 实体化目标类型对象
object obj = Activator.CreateInstance(type);
foreach( var prop in type.GetProperties())
{
// 给目标类型对象的各个属性值赋值
prop.SetValue(obj, dRow[prop.Name],null);
}
list.Add(obj as T) ;
}
return list;
}
}
}
目标方法GetEntityFromDataTable,使用泛型指定待转换的对象类型,并将指定数据的DataTable作为参数传递,返回转换后的对象集合。