using System;
using System.Data;
using System.Reflection;
namespace LEInbound.Application.Helper;
public static class DataTableToList
{
/// <summary>
/// DataTable转换成IEnumerable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dataTable"></param>
/// <returns></returns>
public static IEnumerable<T> ToEnumerable<T>(this DataTable dataTable) where T : class, new()
{
return dataTable.AsEnumerable().Select(s => s.ToModel<T>());
}
/// <summary>
/// DataRow转换成Model
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dataRow"></param>
/// <returns></returns>
public static T ToModel<T>(this DataRow dataRow) where T : class, new()
{
T model = new T();
foreach (var property in model.GetType().GetProperties())
{
foreach (DataColumn key in dataRow.Table.Columns)
{
string columnName = key.ColumnName;
if (!string.IsNullOrEmpty(dataRow[columnName].ToString()))
{
string propertyNameToMatch = columnName;
if (property.Name.ToLower() == propertyNameToMatch.ToLower())
{
Type t = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
object safeValue = (dataRow[columnName] == null) ? null : Convert.ChangeType(dataRow[columnName], t);
property.SetValue(model, safeValue, null);
}
}
}
}
return model;
}
/// <summary>
/// IEnumerable转换成DataTable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="varlist"></param>
/// <returns></returns>
public static DataTable ToDataTable<T>(this IEnumerable<T> varlist) where T : class, new()
{
//定义要返回的DataTable对象
DataTable dtReturn = new DataTable();
//安全性检查
if (varlist == null)
{
return dtReturn;
}
//保存列集合的属性信息数组
PropertyInfo[] oProps = typeof(T).GetProperties();
//循环PropertyInfo数组
foreach (PropertyInfo pi in oProps)
{
//得到属性的类型
Type colType = pi.PropertyType;
//如果属性为泛型类型
if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
{
//获取泛型类型的参数
colType = colType.GetGenericArguments()[0];
}
//将类型的属性名称与属性类型作为DataTable的列数据
dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
}
//循环遍历集合,使用反射获取类型的属性信息
foreach (T rec in varlist)
{
//新建一个用于添加到DataTable中的DataRow对象
DataRow dr = dtReturn.NewRow();
//循环遍历属性集合
foreach (PropertyInfo pi in oProps)
{
//为DataRow中的指定列赋值
dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue(rec, null);
}
//将具有结果值的DataRow添加到DataTable集合中
dtReturn.Rows.Add(dr);
}
//返回DataTable对象
return dtReturn;
}
/// <summary>
/// 去除重复数据
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <typeparam name="TKey"></typeparam>
/// <param name="source"></param>
/// <param name="keySelector"></param>
/// <returns></returns>
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
HashSet<TKey> seenKeys = new HashSet<TKey>();
foreach (TSource element in source)
{
if (seenKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
}
C# List and DataTable 互转
于 2023-06-21 08:46:57 首次发布