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;
|
}
|
}
|
|
}
|