CloudBuilder/CloudBuilder.Core/Utility/DataTableConvertor.cs
owenchen 1c0c83af5f ow
2026-05-12 10:09:31 +08:00

118 lines
3.7 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace CloudBuilder.Core.Utility
{
public class DataTableConvertor
{
/// <summary>
/// DataTable转对象
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static List<T> ConvertToList<T>(DataTable dt) where T : new()
{
// 定义集合
var list = new List<T>();
if (dt == null || 0 == dt.Rows.Count)
{
return list;
}
// 获得此模型的可写公共属性
IEnumerable<PropertyInfo> propertys = typeof(T).GetProperties().Where(u => u.CanWrite);
list = ConvertToEntity<T>(dt, propertys);
return list;
}
private static List<T> ConvertToEntity<T>(DataTable dt, IEnumerable<PropertyInfo> propertys) where T : new()
{
var list = new List<T>();
//遍历DataTable中所有的数据行
foreach (DataRow dr in dt.Rows)
{
if (dr.RowState == DataRowState.Deleted) continue;
var entity = new T();
//遍历该对象的所有属性
foreach (PropertyInfo p in propertys)
{
//将属性名称赋值给临时变量
string tmpName = p.Name;
//检查DataTable是否包含此列列名==对象的属性名)
if (!dt.Columns.Contains(tmpName)) continue;
//取值
object value = dr[tmpName];
//如果非空,则赋给对象的属性
if (value != DBNull.Value)
{
p.SetValue(entity, value, null);
}
}
//对象添加到泛型集合中
list.Add(entity);
}
return list;
}
/// <summary>
/// 对象转DataTable
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
public static DataTable ToDataTable<T>(IList<T> list)
{
return ToDataTable<T>(list, false);
}
public static DataTable ToDataTable<T>(IList<T> list, bool blankOption)
{
Type elementType = typeof(T);
var t = new DataTable();
elementType.GetProperties().ToList().ForEach(propInfo => t.Columns.Add(propInfo.Name, Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType));
if (blankOption)
{
var row = t.NewRow();
t.Rows.Add(row);
}
foreach (T item in list)
{
var row = t.NewRow();
elementType.GetProperties().ToList().ForEach(propInfo => row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value);
t.Rows.Add(row);
}
return t;
}
public static DataTable ToDataTable<T>(T[] list)
{
Type elementType = typeof(T);
var t = new DataTable();
elementType.GetProperties().ToList().ForEach(propInfo => t.Columns.Add(propInfo.Name, Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType));
foreach (T item in list)
{
var row = t.NewRow();
elementType.GetProperties().ToList().ForEach(propInfo => row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value);
t.Rows.Add(row);
}
return t;
}
}
}