csharp:Conversion Between DataTable and List

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/// <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;
        }
    }

  测试数据源:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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;
        }
    }

  测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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;

  

 

posted @   ®Geovin Du Dream Park™  阅读(678)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示