Enumerable转换为DataTable

时间:2023-03-08 21:14:33

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

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Reflection;
namespace H3C.RD.IPDPlan.Common
{
public static class EnumerableConverterExtension
{
/// <summary>
/// 转换为一个DataTable
/// </summary>
/// <typeparam name="TResult"></typeparam>
/// <param name="value"></param>
/// <returns></returns>
public static DataTable ToDataTable<TResult>(this IEnumerable<TResult> value) where TResult : class
{
return value.ToDataTable(Utility.DateTimeFormat.DATETIME_FORMAT_YYYY_MM_DD);
}
/// <summary>
/// 转换为一个DataTable
/// </summary>
/// <typeparam name="TResult"></typeparam>
/// <param name="value"></param>
/// <returns></returns>
public static DataTable ToDataTable<TResult>(this IEnumerable<TResult> value,string format) where TResult : class
{
if (string.IsNullOrEmpty(format))
{
format = Utility.DateTimeFormat.DATETIME_FORMAT_YYYY_MM_DD;
}
//创建属性的集合
List<PropertyInfo> pList = new List<PropertyInfo>();
//获得反射的入口
Type type = typeof(TResult); DataTable dt = new DataTable();
//把所有的public属性加入到集合 并添加DataTable的列
Array.ForEach<PropertyInfo>(type.GetProperties(), p =>
{
pList.Add(p);
if (p.PropertyType.IsGenericType)
{
dt.Columns.Add(p.Name);
}
else
{
dt.Columns.Add(p.Name, p.PropertyType);
}
});
if (null != value)
{
foreach (var item in value)
{
//创建一个DataRow实例
DataRow row = dt.NewRow();
//给row 赋值
pList.ForEach(p => row[p.Name] = (p.GetValue(item, null) is DateTime) ? Utility.FormatDateTime(p.GetValue(item, null), format) : p.GetValue(item, null));
//加入到DataTable
dt.Rows.Add(row);
}
}
return dt;
}
}
}