89 lines
3.1 KiB
C#
89 lines
3.1 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Data;
|
|
using System.Linq;
|
|
using System.Reflection;
|
|
|
|
namespace Falcon.SugarApi
|
|
{
|
|
/// <summary>
|
|
/// 枚举扩展
|
|
/// </summary>
|
|
public static class IEnumerableExtend
|
|
{
|
|
/// <summary>
|
|
/// 枚举转换为DataTable
|
|
/// </summary>
|
|
/// <param name="source">数据枚举</param>
|
|
/// <returns>转换后Datatable</returns>
|
|
/// <exception cref="ArgumentNullException">参数为Null</exception>
|
|
public static DataTable ToDataTable(this IEnumerable<object> source) {
|
|
_ = source ?? throw new ArgumentNullException(nameof(source));
|
|
var dt = new DataTable();
|
|
if (source.Count() == 0) {
|
|
return dt;
|
|
}
|
|
for (int i = 0; i < source.Count(); i++) {
|
|
var item = source.ToArray()[i];
|
|
foreach (PropertyInfo pro in item.GetType().GetProperties()) {
|
|
if (!dt.Columns.Contains(pro.Name)) {
|
|
dt.Columns.Add(new DataColumn {
|
|
ColumnName = pro.Name,
|
|
DataType = pro.PropertyType,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
foreach (var i in source) {
|
|
var row = dt.NewRow();
|
|
foreach (var p in i.GetType().GetProperties()) {
|
|
if (p.CanRead) {
|
|
var val = p.GetValue(i);
|
|
try {
|
|
row[p.Name] = val;
|
|
}
|
|
catch (Exception ex) {
|
|
throw new Exception($"值设置失败!{p.Name}:{val}", ex);
|
|
}
|
|
}
|
|
}
|
|
dt.Rows.Add(row);
|
|
}
|
|
return dt;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 枚举转换为DataTable
|
|
/// </summary>
|
|
/// <typeparam name="T">枚举的元素类型</typeparam>
|
|
/// <param name="source">原数据</param>
|
|
/// <returns>转换后Datatable</returns>
|
|
/// <exception cref="ArgumentNullException">参数为Null</exception>
|
|
public static DataTable ToDataTable<T>(this IEnumerable<T> source) {
|
|
_ = source ?? throw new ArgumentNullException(nameof(source));
|
|
var type = typeof(T);
|
|
var dt = new DataTable();
|
|
var pros = typeof(T).GetProperties();
|
|
foreach (PropertyInfo p in pros) {
|
|
if (p.CanRead) {
|
|
dt.Columns.Add(new DataColumn {
|
|
ColumnName = p.Name,
|
|
DataType = p.PropertyType,
|
|
});
|
|
}
|
|
}
|
|
foreach (var i in source) {
|
|
var row = dt.NewRow();
|
|
foreach (var p in pros) {
|
|
if (p.CanRead) {
|
|
var val = p.GetValue(i);
|
|
row[p.Name] = val;
|
|
}
|
|
}
|
|
dt.Rows.Add(row);
|
|
}
|
|
return dt;
|
|
}
|
|
}
|
|
}
|