using System.Collections;
using System.Data;
namespace ShrlAlgo.Toolkit.Core.Extensions;
public static class DataTableExtensions
{
///
/// 获取数据
///
///
///
///
///
public static string GetValue(this DataTable dt, int row, int column)
{
return dt != null ? dt.Rows[row][column].ToString() : string.Empty;
}
///
/// 获取值
///
///
///
///
///
public static string GetValue(this DataRow dr, int column)
{
return dr == null ? throw new ArgumentNullException(nameof(dr)) : dr[column].ToString();
}
///
/// 设置值
///
///
///
///
///
public static void SetValue(this DataTable dt, int row, int column, object value)
{
dt.Rows[row][column] = value;
}
///
/// 设置值
///
///
///
///
///
public static void SetValue(this DataRow dr, int column, object value)
{
if (dr == null)
{
throw new ArgumentNullException(nameof(dr));
}
dr[column] = value;
}
///
/// 转实体,属性名必须与列名相同
///
///
///
///
public static List ToEntities(this DataTable table)
where T : new()
{
var entities = new List();
if (table == null)
{
return null;
}
foreach (DataRow row in table.Rows)
{
T entity = new();
foreach (var item in entity.GetType().GetProperties())
{
if (table.Columns.Contains(item.Name))
{
if (DBNull.Value != row[item.Name])
{
var newType = item.PropertyType;
//判断type类型是否为泛型,因为nullable是泛型类,
if (newType.IsGenericType && newType.GetGenericTypeDefinition() == typeof(Nullable<>)) //判断convertsionType是否为nullable泛型类
{
//如果type为nullable类,声明一个NullableConverter类,该类提供从Nullable类到基础基元类型的转换
var nullableConverter = new System.ComponentModel.NullableConverter(newType);
//将type转换为nullable对的基础基元类型
newType = nullableConverter.UnderlyingType;
}
item.SetValue(entity, Convert.ChangeType(row[item.Name], newType), null);
}
}
}
entities.Add(entity);
}
return entities;
}
///
/// 将指定的集合转换成DataTable。
///
/// 将指定的集合。
/// 返回转换后的DataTable。
public static DataTable ToDataTable(this IList list)
{
var table = new DataTable();
var properties = list[0].GetType().GetProperties();
foreach (var pi in properties)
{
var pt = pi.PropertyType;
if (pt.IsGenericType && pt.GetGenericTypeDefinition() == typeof(Nullable<>))
{
pt = pt.GetGenericArguments()[0];
}
table.Columns.Add(new DataColumn(pi.Name, pt));
}
for (var i = 0; i < list.Count; i++)
{
var tempList = new ArrayList();
foreach (var pi in properties)
{
var obj = pi.GetValue(list[i], null);
tempList.Add(obj);
}
var array = tempList.ToArray();
table.LoadDataRow(array, true);
}
return table;
}
}