DataTable dt= DataTable.Clone()
foreach(DataTable dtItem in List<DataTable>)
{
foreach(DataRow dr in dtItem.rows)
{
//这里importRow是方法,dr是你要插入的方法,dt是你要散搜合并的表,就是你最终得到的表。
冲亏历 dt.importRow(dr) 空橘
}
}
using Systemusing System.Collections.Generic
using System.Linq
using System.Text
using System.Data
using System.Collections
using System.Reflection
namespace DatableToList
{
class ConvertHelper<T>where T : new()
{
/// <summary>
/// 利用反射和泛型
/// </summary>
/// <param name="<a href="https://www.baidu.com/s?wd=dt&tn=44039180_cpr&fenlei=mv6quAkxTZn0IZRqIHckPjm4nH00T1YLmWb4PA7Bm1TknycYnHTY0ZwV5Hcvrjm3rH6sPfKWUMw85HfYnjn4nH6sgvPsT6KdThsqpZwYTjCEQLGCpyw9Uz4Bmy-bIi4WUvYETgN-TLwGUv3Erj04P1D3rjDzP10sPHT3PjRz" target="_blank" class="baidu-highlight">dt</a>"></param>
/// <returns><大消/returns>
public static List<T>ConvertToList(DataTable <a href="https://www.baidu.com/s?wd=dt&tn=44039180_cpr&fenlei=mv6quAkxTZn0IZRqIHckPjm4nH00T1YLmWb4PA7Bm1TknycYnHTY0ZwV5Hcvrjm3rH6sPfKWUMw85HfYnjn4nH6sgvPsT6KdThsqpZwYTjCEQLGCpyw9Uz4Bmy-bIi4WUvYETgN-TLwGUv3Erj04P1D3rjDzP10sPHT3PjRz" target="_blank" class="蔽昌baidu-highlight">dt</a>)
{
// 定义集合
List<T><a href="https://www.baidu.com/s?wd=ts&tn=44039180_cpr&fenlei=mv6quAkxTZn0IZRqIHckPjm4nH00T1YLmWb4PA7Bm1TknycYnHTY0ZwV5Hcvrjm3rH6sPfKWUMw85HfYnjn4nH6sgvPsT6KdThsqpZwYTjCEQLGCpyw9Uz4Bmy-bIi4WUvYETgN-TLwGUv3Erj04P1D3rjDzP10sPHT3PjRz" target="_blank" class="baidu-highlight">ts</a>= new List<T>()
// 获得此模型的类型
Type type = typeof(T)
//定义一个临时变量
string tempName = string.Empty
//遍历宏仿扒DataTable中所有的数据行
foreach (DataRow dr in <a href="https://www.baidu.com/s?wd=dt&tn=44039180_cpr&fenlei=mv6quAkxTZn0IZRqIHckPjm4nH00T1YLmWb4PA7Bm1TknycYnHTY0ZwV5Hcvrjm3rH6sPfKWUMw85HfYnjn4nH6sgvPsT6KdThsqpZwYTjCEQLGCpyw9Uz4Bmy-bIi4WUvYETgN-TLwGUv3Erj04P1D3rjDzP10sPHT3PjRz" target="_blank" class="baidu-highlight">dt</a>.Rows)
{
T t = new T()
// 获得此模型的公共属性
PropertyInfo[] 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)
}
}
//对象添加到泛型集合中
<a href="https://www.baidu.com/s?wd=ts&tn=44039180_cpr&fenlei=mv6quAkxTZn0IZRqIHckPjm4nH00T1YLmWb4PA7Bm1TknycYnHTY0ZwV5Hcvrjm3rH6sPfKWUMw85HfYnjn4nH6sgvPsT6KdThsqpZwYTjCEQLGCpyw9Uz4Bmy-bIi4WUvYETgN-TLwGUv3Erj04P1D3rjDzP10sPHT3PjRz" target="_blank" class="baidu-highlight">ts</a>.Add(t)
}
return <a href="https://www.baidu.com/s?wd=ts&tn=44039180_cpr&fenlei=mv6quAkxTZn0IZRqIHckPjm4nH00T1YLmWb4PA7Bm1TknycYnHTY0ZwV5Hcvrjm3rH6sPfKWUMw85HfYnjn4nH6sgvPsT6KdThsqpZwYTjCEQLGCpyw9Uz4Bmy-bIi4WUvYETgN-TLwGUv3Erj04P1D3rjDzP10sPHT3PjRz" target="_blank" class="baidu-highlight">ts</a>
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)