using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
namespace Falcon.SugarApi
{
///
/// 枚举扩展
///
public static class IEnumerableExtend
{
///
/// 枚举转换为DataTable
///
/// 数据枚举
/// 转换后Datatable
/// 参数为Null
public static DataTable ToDataTable(this IEnumerable source) {
_=source??throw new ArgumentNullException(nameof(source));
var dt = new DataTable();
if(source.Count()==0) {
return dt;
}
for(int i = 0;i
/// 枚举转换为DataTable
///
/// 枚举的元素类型
/// 原数据
/// 转换后Datatable
/// 参数为Null
public static DataTable ToDataTable(this IEnumerable 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;
}
///
/// 对枚举进行缩减,并返回缩减后的结果。
///
/// 枚举的类型
/// 缩减结果类型
/// 原枚举
/// 缩减方法
/// 缩减初始值
/// 缩减结果
public static TR Reduce(this IEnumerable source,Func reduceFunc,TR initialValue) {
if(reduceFunc==null) {
throw new ArgumentNullException(nameof(reduceFunc));
}
var result = initialValue;
foreach(var i in source) {
result=reduceFunc(result,i);
}
return result;
}
///
/// 对枚举进行缩减,并返回缩减后的结果。
///
/// 枚举的类型
/// 缩减结果类型
/// 原枚举
/// 缩减方法
/// 缩减初始值
/// 缩减结果
public static TR Reduce(this IEnumerable source,TR initialValue,Func reduceFunc) {
if(reduceFunc==null) {
throw new ArgumentNullException(nameof(reduceFunc));
}
var result = initialValue;
if(source.IsNull()) {
}
foreach(var i in source) {
result=reduceFunc(result,i);
}
return result;
}
///
/// 返回枚举是否为null或者集合无元素
///
/// 枚举的元素类型
/// 枚举对象
/// 为null或者无元素返回True,否则False
public static bool IsNullOrEmpty([AllowNull] this IEnumerable values) => values==null||values.Count()==0;
///
/// 返回枚举是否不为null或者集合无元素,结果是对IsNullOrEmpty去反。
///
/// 枚举的元素类型
/// 枚举对象
/// 枚举不为null或者无元素返回True,否则False
public static bool IsNotNullOrEmpty([AllowNull] this IEnumerable values) => !values.IsNullOrEmpty();
}
}