管道基础大数据平台系统开发-【CS】-ExportMap
13693261870
2024-09-03 3cfb6aa02516135fb174ab1b30620f2007924663
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Web;
 
namespace JiangSu.cs
{
    /// <summary>
    /// DataTable与实体类相互转换
    /// </summary>
    public class ModelHandler
    {
        /// <summary>
        /// 填充对象列表
        /// </summary>
        public static List<T> FillModel<T>(DataTable dt) where T : new()
        {
            if (dt == null || dt.Rows.Count == 0)
            {
                return null;
            }
 
            List<T> list = new List<T>();
            BindingFlags flag = BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance;
            PropertyInfo[] pis = typeof(T).GetProperties();
 
            foreach (DataRow dr in dt.Rows)
            {
                T t = new T();
                foreach (PropertyInfo pi in pis)
                {
                    object val = dr[pi.Name] == DBNull.Value ? null : dr[pi.Name];
                    t.GetType().GetProperty(pi.Name, flag).SetValue(t, val, null);
                }
 
                list.Add(t);
            }
 
            return list;
        }
 
        /// <summary>
        /// 填充DataTable
        /// </summary>
        public static DataTable FillDataTable<T>(List<T> list) where T : new()
        {
            if (list == null || list.Count == 0)
            {
                return null;
            }
 
            DataTable dt = CreateDataTable<T>();
            PropertyInfo[] pis = typeof(T).GetProperties();
 
            foreach (T t in list)
            {
                DataRow dr = dt.NewRow();
                foreach (PropertyInfo pi in pis)
                {
                    dr[pi.Name] = pi.GetValue(t, null);
                }
            }
 
            return dt;
        }
 
        /// <summary>
        /// 创建DataTable
        /// </summary>
        public static DataTable CreateDataTable<T>() where T : new()
        {
            DataTable dt = new DataTable(typeof(T).Name);
 
            PropertyInfo[] pis = typeof(T).GetProperties();
            foreach (PropertyInfo pi in pis)
            {
                dt.Columns.Add(new DataColumn(pi.Name, pi.PropertyType));
            }
 
            return dt;
        }
    }
}