1 Star 0 Fork 23

刘小吉/代码片段

forked from Sunday/代码片段 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
DataTableExtensions.cs 4.23 KB
一键复制 编辑 原始数据 按行查看 历史
Sunday 提交于 2022-05-27 08:01 . 上传datatable转换扩展方法
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace BoYuan.Framework.Uitility.Extensions
{
public static class DataTableExtensions
{
/// <summary>
/// Linq匿名对象集合转成DataTable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="query">The query.</param>
/// <returns></returns>
public static DataTable ToDataTable<T>(this IEnumerable<T> query)
{
var props = typeof(T).GetProperties();
var dt = new DataTable();
dt.Columns.AddRange(props.Select(p => new DataColumn(p.Name, p.PropertyType)).ToArray());
if (query.Any())
{
for (int i = 0; i < query.Count(); i++)
{
ArrayList tempList = new ArrayList();
foreach (PropertyInfo pi in props)
{
object obj = pi.GetValue(query.ElementAt(i), null);
tempList.Add(obj);
}
object[] array = tempList.ToArray();
dt.LoadDataRow(array, true);
}
}
return dt;
}
/// <summary>
/// DataTable转List
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <returns></returns>
public static IList<T> DtToList<T>(this DataTable dt) where T : new()
{
// 定义集合
IList<T> ts = new List<T>();
// 获得此模型的类型
Type type = typeof(T);
string tempName = "";
T t;
PropertyInfo[] propertys;
foreach (DataRow dr in dt.Rows)
{
t= new T();
// 获得此模型的公共属性
propertys = t.GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
tempName = pi.Name; // 检查DataTable是否包含此列
if (dt.Columns.Contains(tempName))
{
// 判断此属性是否有Setter
if (!pi.CanWrite) continue;
object value = dr[tempName];
if (value != DBNull.Value)
pi.SetValue(t, value, null);
}
}
ts.Add(t);
}
return ts;
}
/// <summary>
/// DataRow对象转换成Object<T>对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="row"></param>
/// <returns></returns>
public static T DataRowToObject<T>(this DataRow row)
{
T obj = default(T);
if (row != null)
{
obj = Activator.CreateInstance<T>();
foreach (DataColumn column in row.Table.Columns)
{
PropertyInfo prop = obj.GetType().GetProperty(column.ColumnName);
try
{
object value = row[column.ColumnName];
prop.SetValue(obj, value);
}
catch (Exception ex)
{
throw ex;
}
}
}
return obj;
}
/// <summary>
/// 将DataRow[]转换成DataTable
/// </summary>
/// <param name="rows"></param>
/// <returns></returns>
public static DataTable ToDataTable(this DataRow[] rows)
{
if (rows == null || rows.Length == 0) return null;
DataTable tmp = rows[0].Table.Clone(); // 复制DataRow的表结构
foreach (DataRow row in rows)
tmp.Rows.Add(row.ItemArray); // 将DataRow添加到DataTable中
return tmp;
}
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C#
1
https://gitee.com/notify/code_snippet.git
git@gitee.com:notify/code_snippet.git
notify
code_snippet
代码片段
master

搜索帮助