Enumerable转换为DataTable

今天在项目组公共类库中发现一个 Enumerable类型转换为DataTable,写的挺精简的,拿出来跟大家共享一下。

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Data;
 6 using System.Reflection;
 7 namespace H3C.RD.IPDPlan.Common
 8 {
 9     public static class EnumerableConverterExtension
10     {
11         /// <summary>
12         /// 转换为一个DataTable
13         /// </summary>
14         /// <typeparam name="TResult"></typeparam>
15         /// <param name="value"></param>
16         /// <returns></returns>
17         public static DataTable ToDataTable<TResult>(this IEnumerable<TResult> value) where TResult : class
18         {
19             return value.ToDataTable(Utility.DateTimeFormat.DATETIME_FORMAT_YYYY_MM_DD);
20         }
21         /// <summary>
22         /// 转换为一个DataTable
23         /// </summary>
24         /// <typeparam name="TResult"></typeparam>
25         /// <param name="value"></param>
26         /// <returns></returns>
27         public static DataTable ToDataTable<TResult>(this IEnumerable<TResult> value,string format) where TResult : class
28         {
29             if (string.IsNullOrEmpty(format))
30             {
31                 format = Utility.DateTimeFormat.DATETIME_FORMAT_YYYY_MM_DD;
32             }
33             //创建属性的集合
34             List<PropertyInfo> pList = new List<PropertyInfo>();
35             //获得反射的入口
36             Type type = typeof(TResult);
37            
38             DataTable dt = new DataTable();
39             //把所有的public属性加入到集合 并添加DataTable的列
40             Array.ForEach<PropertyInfo>(type.GetProperties(), p =>
41             {
42                 pList.Add(p);
43                 if (p.PropertyType.IsGenericType)
44                 {
45                     dt.Columns.Add(p.Name);
46                 }
47                 else
48                 {
49                     dt.Columns.Add(p.Name, p.PropertyType);
50                 }
51             });
52             if (null != value)
53             {
54                 foreach (var item in value)
55                 {
56                     //创建一个DataRow实例
57                     DataRow row = dt.NewRow();
58                     //给row 赋值
59                     pList.ForEach(p => row[p.Name] = (p.GetValue(item, null) is DateTime) ? Utility.FormatDateTime(p.GetValue(item, null), format) : p.GetValue(item, null));
60                     //加入到DataTable
61                     dt.Rows.Add(row);
62                 }
63             }
64             return dt;
65         }
66     }
67 }

 

posted @ 2013-06-18 19:11  Eric.Chen  阅读(1319)  评论(0编辑  收藏  举报
作者:Eric.Chen
出处:https://www.cnblogs.com/lc-chenlong
如果喜欢作者的文章,请关注“写代码的猿”订阅号以便第一时间获得最新内容。本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。