ningshuxia
2022-10-08 afedb8fd4e17a5a911deee3dae04a10a93e6a39a
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
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
 
namespace IStation.Extensions
{
    /// <summary>
    /// DataTable拓展
    /// </summary>
    public static class DataTableExtension
    {
        /// <summary>
        /// 转化为可枚举对象
        /// </summary>
        public static IEnumerable<T> ToEnumerable<T>(this DataTable dt) where T : new()
        {
            foreach (DataRow dr in dt.Rows)
            {
                T t = new T();
                PropertyInfo[] properties = t.GetType().GetProperties();
                foreach (PropertyInfo pro in properties)
                {
                    //判断DataTable是否包含此列
                    if (dt.Columns.Contains(pro.Name))
                    {
                        //判断此属性是否有Setter
                        if (!pro.CanWrite)
                            continue;
                        object value = dr[pro.Name];
                        if (value != DBNull.Value)
                            pro.SetValue(t, value, null);
                    }
                }
                yield return t;
            }
        }
 
 
    }
 
}