泛型列表转ToDataTable

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
/// <summary>
    /// 列表转换DataTable助手
    /// </summary>
    public static class ListToDatatableHelper
    {
        /// <summary>
        /// 将泛型实体列表转换为DataTable
        /// </summary>
        public static DataTable ToDataTable<T>(List<T> items)
        {
            var tb = new DataTable(typeof(T).Name);
 
            PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
 
            foreach (PropertyInfo prop in props)
            {
                Type t = GetCoreType(prop.PropertyType);
                tb.Columns.Add(prop.Name, t);
            }
 
            foreach (T item in items)
            {
                var values = new object[props.Length];
 
                for (int i = 0; i < props.Length; i++)
                {
                    values[i] = props[i].FastGetValue(item);
                }
 
                tb.Rows.Add(values);
            }
 
            return tb;
        }
 
        /// <summary>
        /// 获取实际类型
        /// </summary>
        public static Type GetCoreType(Type t)
        {
            if (t != null && IsNullable(t))
            {
                if (t.IsValueType == false)
                {
                    return t;
                }
                return Nullable.GetUnderlyingType(t);
            }
            return t;
        }
 
        /// <summary>
        /// 判断是否是可空类型
        /// </summary>
        public static bool IsNullable(Type t)
        {
            return t.IsValueType == false || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
        }
    }

  

posted @   昵称已存在嘿  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
欢迎阅读『泛型列表转ToDataTable』
欢迎阅读『泛型列表转ToDataTable』
点击右上角即可分享
微信分享提示