hudong
2025-07-04 67c7f0449f57933c26d785c277ddcd539c899b25
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
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
 
namespace HH.WCS.Mobox3.pinggao.core
{
    public static class ListExtensions
    {
        public static DataTable ToDataTable<T>(this List<T> items)
        {
            DataTable dataTable = new DataTable(typeof(T).Name);
 
            // 获取类型属性(排除复杂类型)
            PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
 
            // 创建列(仅处理基元类型和字符串)
            foreach (PropertyInfo prop in props)
            {
                if (IsSimpleType(prop.PropertyType))
                {
                    // 处理Nullable类型
                    Type colType = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
                    dataTable.Columns.Add(prop.Name, colType);
                }
            }
 
            // 添加数据行
            foreach (T item in items)
            {
                DataRow row = dataTable.NewRow();
                foreach (PropertyInfo prop in props)
                {
                    if (IsSimpleType(prop.PropertyType))
                    {
                        object value = prop.GetValue(item, null) ?? DBNull.Value;
                        row[prop.Name] = value;
                    }
                }
                dataTable.Rows.Add(row);
            }
            return dataTable;
        }
 
        private static bool IsSimpleType(Type type)
        {
            // 处理Nullable类型
            Type underlyingType = Nullable.GetUnderlyingType(type) ?? type;
 
            return underlyingType.IsPrimitive
                || underlyingType == typeof(string)
                || underlyingType == typeof(decimal)
                || underlyingType == typeof(DateTime)
                || underlyingType == typeof(TimeSpan)
                || underlyingType == typeof(Guid)
                || underlyingType.IsEnum;
        }
    }
  
}