using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication12
{
public class Student
{
public int? StuNo { get; set; }
public string Name { get; set; }
public string Sex { get; set; }
public int Age { get; set; }
public override string ToString()
{
return this.StuNo + ":" + this.Name + ":" + this.Sex + ":" + this.Age;
}
}
public static class DataTableAndListExetension
{
public static List<T> ToList<T>(this DataTable table) where T:new()
{
List<T> list = new List<T>();
Type t = typeof(T);
PropertyInfo[] ps = t.GetProperties();
foreach (DataRow dr in table.Rows)
{
T obj = new T();
foreach (DataColumn col in table.Columns)
{
foreach (PropertyInfo p in ps)
{
if (p.Name == col.ColumnName)
{
if (!p.PropertyType.IsGenericType)
{
p.SetValue(obj,string.IsNullOrEmpty(dr[col.ColumnName].ToString())?null:Convert.ChangeType(dr[col.ColumnName],p.PropertyType));
}
else
{
Type genericTypeDefinition= p.PropertyType.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
p.SetValue(obj,string.IsNullOrEmpty(dr[col.ColumnName].ToString())?null:Convert.ChangeType(dr[col.ColumnName],Nullable.GetUnderlyingType(p.PropertyType)));
}
}
}
}
}
list.Add(obj);
}
return list;
return null;
}
public static DataTable ToDataTable<T>(this List<T> list)
{
Type t = typeof(T);
PropertyInfo[] ps = t.GetProperties();
DataTable dt = new DataTable();
foreach (PropertyInfo p in ps)
{
Type type = p.PropertyType;
if (!p.PropertyType.IsGenericType)
{
dt.Columns.Add(p.Name, type);
}
else
{
Type genericTypeDefinition = p.PropertyType.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
dt.Columns.Add(p.Name,Nullable.GetUnderlyingType(p.PropertyType));
}
}
foreach (T stu in list)
{
DataRow dr = dt.NewRow();
foreach (PropertyInfo p in ps)
{
dr[p.Name] = p.GetValue(stu);
}
dt.Rows.Add(dr);
}
return dt;
return null;
}
}
public class Program
{
public static List<Student> StuList = new List<Student>();
static void Main(string[] args)
{
StuList.Add(new Student() { StuNo=1, Name="1",Sex="1",Age=1});
StuList.Add(new Student() { StuNo = 2, Name = "2", Sex = "2", Age = 2 });
StuList.Add(new Student() { StuNo = 3, Name = "3", Sex = "3", Age = 3 });
StuList.Add(new Student() { StuNo = 4, Name = "4", Sex = "4", Age = 4 });
StuList.Add(new Student() { StuNo = 5, Name = "5", Sex = "5", Age = 5 });
DataTable dt = StuList.ToDataTable<Student>();
DataTable dt2 = dt.Clone();
List<Student> stus= dt.ToList<Student>();
Console.WriteLine(" dt.ToList<Student>()输出学生列表");
stus.ForEach(a => { Console.WriteLine(a.ToString()); });
Console.ReadLine();
foreach (DataRow odr in dt.Rows)
{
DataRow ndr = dt2.NewRow();
ndr.ItemArray = odr.ItemArray;
dt2.ImportRow(odr);
}
}
}
}