分享
 
 
 

csharp:Conversion Between DataTable and List

王朝学院·作者佚名  2016-05-20
窄屏简体版  字體: |||超大  

csharp:Conversion Between DataTable and List/// <summary> /// http://www.codePRoject.com/Tips/784090/Conversion-Between-DataTable-and-List-in-Csharp /// </summary> public static class ExtensionUtility { /// <summary> /// Converts List To DataTable /// </summary> /// <typeparam name="TSource"></typeparam> /// <param name="data"></param> /// <returns></returns> public static DataTable ToDataTable<TSource>(this IList<TSource> data) { DataTable dataTable = new DataTable(typeof(TSource).Name); PropertyInfo[] props = typeof(TSource).GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo prop in props) { dataTable.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType); } foreach (TSource item in data) { var values = new object[props.Length]; for (int i = 0; i < props.Length; i++) { values[i] = props[i].GetValue(item, null); } dataTable.Rows.Add(values); } return dataTable; } /// <summary> /// Converts DataTable To List /// </summary> /// <typeparam name="TSource"></typeparam> /// <param name="dataTable"></param> /// <returns></returns> public static List<TSource> ToList<TSource>(this DataTable dataTable) where TSource : new() { var dataList = new List<TSource>(); const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic; var objFieldNames = (from PropertyInfo aProp in typeof(TSource).GetProperties(flags) select new { Name = aProp.Name, Type = Nullable.GetUnderlyingType(aProp.PropertyType) ?? aProp.PropertyType }).ToList(); var dataTblFieldNames = (from DataColumn aHeader in dataTable.Columns select new { Name = aHeader.ColumnName, Type = aHeader.DataType }).ToList(); var commonFields = objFieldNames.Intersect(dataTblFieldNames).ToList(); foreach (DataRow dataRow in dataTable.AsEnumerable().ToList()) { var aTSource = new TSource(); foreach (var aField in commonFields) { PropertyInfo propertyInfos = aTSource.GetType().GetProperty(aField.Name); var value = (dataRow[aField.Name] == DBNull.Value) ? null : dataRow[aField.Name]; //if database field is nullable propertyInfos.SetValue(aTSource, value, null); } dataList.Add(aTSource); } return dataList; } }

测试数据源:

public class Student { public long Id { get; set; } public string Name { get; set; } public short Age { get; set; } public DateTime DateOfCreation { get; set; } public bool? IsActive { get; set; } } public class Teacher { public long Id { get; set; } public string Name { get; set; } public Nullable<int> DepartmentId { get; set; } } public class Data { public static List<Student> GetStudents() { var list = new List<Student> { new Student {Id = 1, Name = "Smith", Age = 18, DateOfCreation = DateTime.Now, IsActive = true}, new Student {Id = 2, Name = "Hook", Age = 16, DateOfCreation = DateTime.Now.AddDays(-1), IsActive = true}, new Student {Id = 3, Name = "Jhon", Age = 15, DateOfCreation = DateTime.Now.AddDays(-2), IsActive = true}, new Student {Id = 4, Name = "Alan", Age = 21, DateOfCreation = DateTime.Now.AddDays(-3), IsActive = true} }; return list; } public static List<Teacher> GetTeachers() { var list = new List<Teacher> { new Teacher {Id = 1, Name = "Smith", DepartmentId = 18 }, new Teacher {Id = 2, Name = "Hook", DepartmentId = 16 }, new Teacher {Id = 3, Name = "Jhon", DepartmentId = 15 }, new Teacher {Id = 4, Name = "Alan", DepartmentId = 21 } }; return list; } public static DataTable DbNullInt() { DataTable table = new DataTable(); table.Columns.Add("Id", typeof(long)); table.Columns.Add("Name", typeof(string)); DataColumn column; column = new DataColumn("DepartmentId", System.Type.GetType("System.Int32")); column.AllowDBNull = true; table.Columns.Add(column); table.Rows.Add(1, "Smith", DBNull.Value); table.Rows.Add(2, "Hook", 1); return table; } }

测试:

List<Student> students = Data.GetStudents(); /*List to DataTable conversion*/ DataTable studentTbl = students.ToDataTable(); /*DataTable to List conversion*/ List<Student> newStudents = studentTbl.ToList<Student>();//ExtensionUtility.ToList<Student>(newStudents); this.dataGridView1.DataSource = newStudents; /*List to DataTable conversion*/ DataTable teacherTbl = Data.DbNullInt(); /*DataTable to List conversion*/ List<Teacher> newTeachers = teacherTbl.ToList<Teacher>(); this.dataGridView2.DataSource = newTeachers;

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有