提交 | 用户 | 时间
|
e46d3b
|
1 |
using System; |
懒 |
2 |
using System.Collections.Generic; |
|
3 |
using System.Data; |
|
4 |
using System.Linq; |
|
5 |
using System.Reflection; |
|
6 |
using System.Text; |
|
7 |
|
|
8 |
namespace YX.BLL |
|
9 |
{ |
|
10 |
public class ListToDataTable |
|
11 |
{ |
|
12 |
public static DataTable ListModelToDataTable<T>(List<T> entitys) |
|
13 |
{ |
|
14 |
|
|
15 |
//检查实体集合不能为空 |
|
16 |
if (entitys == null || entitys.Count < 1) |
|
17 |
{ |
|
18 |
return new DataTable(); |
|
19 |
} |
|
20 |
|
|
21 |
//取出第一个实体的所有Propertie |
|
22 |
Type entityType = entitys[0].GetType(); |
|
23 |
PropertyInfo[] entityProperties = entityType.GetProperties(); |
|
24 |
|
|
25 |
//生成DataTable的structure |
|
26 |
//生产代码中,应将生成的DataTable结构Cache起来,此处略 |
|
27 |
DataTable dt = new DataTable("dt"); |
|
28 |
for (int i = 0; i < entityProperties.Length; i++) |
|
29 |
{ |
|
30 |
//dt.Columns.Add(entityProperties[i].Name, entityProperties[i].PropertyType); |
|
31 |
dt.Columns.Add(entityProperties[i].Name); |
|
32 |
} |
|
33 |
|
|
34 |
//将所有entity添加到DataTable中 |
|
35 |
foreach (object entity in entitys) |
|
36 |
{ |
|
37 |
//检查所有的的实体都为同一类型 |
|
38 |
if (entity.GetType() != entityType) |
|
39 |
{ |
|
40 |
throw new Exception("要转换的集合元素类型不一致"); |
|
41 |
} |
|
42 |
object[] entityValues = new object[entityProperties.Length]; |
|
43 |
for (int i = 0; i < entityProperties.Length; i++) |
|
44 |
{ |
|
45 |
entityValues[i] = entityProperties[i].GetValue(entity, null); |
|
46 |
|
|
47 |
} |
|
48 |
dt.Rows.Add(entityValues); |
|
49 |
} |
|
50 |
return dt; |
|
51 |
} |
|
52 |
} |
|
53 |
} |