using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
namespace DAL
{
/// <summary>
/// 用于给 DataTable和 DataRow扩展方法
/// </summary>
public static class TableExtensionMethod
{
/// <summary>
/// 功能:
/// 给DataTable扩展了一个方法,能够将DataTable中的行转变为对应的class对象,并封装到List集合中;
/// </summary>
/// <typeparam name="T">需要转变成为的class类型</typeparam>
/// <param name="table">传入的DataTable对象</param>
/// <returns>返回一个封装了对应class的List集合</returns>
public static List<T> TableToClass<T>(this DataTable table)
{
Type type = typeof(T);
PropertyInfo[] propArr = type.GetProperties();//获取所有属性
List<T> list = new List<T>();
DataRowCollection rows = table.Rows;
int len = rows[0].ItemArray.Length;//获取第一行的列数,即class的属性个数
for (int i = 0; i < rows.Count; i++)
{
T t = (T)Activator.CreateInstance(type);
for (int j = 0; j < len; j++)//这里之所以不使用propArr.Length,是因为有些Models的属性在数据表中不存在对应的列
{
propArr[j].SetValue(t, rows[i][j]);
}
list.Add(t);
t = default(T);
}
return list;
}
/// <summary>
/// 功能:
/// DataRow的扩展方法;
/// 能够将DataRow对象封装到泛型对象中
/// </summary>
/// <typeparam name="T">需要转换成为的class类型</typeparam>
/// <param name="row">被转换的行</param>
/// <returns>封装了行数据的class对象</returns>
public static T RowToClass<T>(this DataRow row)
{
//Type type = Assembly.Load(classFullName).GetType();
Type type = typeof(T);
T t = (T)Activator.CreateInstance(type);
PropertyInfo[] propArr = type.GetProperties();
int len = row.ItemArray.Length;
for (int i = 0; i < len; i++)
{
propArr[i].SetValue(t, row[i]);
}
return t;
}
/// <summary>
/// 功能:
/// DataRowCollection的扩展方法;
/// 能够将DataRowCollection对象封装到泛型List集合中
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="rows"></param>
/// <returns></returns>
public static List<T> RowToClass<T>(this DataRow row, DataRow[] rowArr)
{
Type type = typeof(T);
PropertyInfo[] propArr = type.GetProperties();
int len = rowArr[0].ItemArray.Length;//获取数据表第一行的列数,即属性个数
List<T> list = new List<T>();
for (int i = 0; i < rowArr.Length; i++)
{
T t = (T)Activator.CreateInstance(type);
for (int j = 0; j < len; j++)
{
propArr[j].SetValue(t, rowArr[i][j]);
}
list.Add(t);
t = default(T);
}
return list;
}
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有