c#的datatable转list示例
c#的datatable转list示例
发布时间:2016-12-28 来源:查字典编辑
摘要:复制代码代码如下:usingSystem;usingSystem.Collections.Generic;usingSystem.Data;...

复制代码 代码如下:

using System;

using System.Collections.Generic;

using System.Data;

using System.Reflection;

namespace jdrz.HumanIdentify

{

public class Helper

{

/// <summary>

/// DataTable 转换为List 集合

/// </summary>

/// <typeparam name="TResult">类型</typeparam>

/// <param name="dt">DataTable</param>

/// <returns></returns>

public static List<TResult> ToList<TResult>(DataTable dt) where TResult : class, new()

{

//创建一个属性的列表

var prlist = new List<PropertyInfo>();

//获取TResult的类型实例 反射的入口

var t = typeof(TResult);

//获得TResult 的所有的Public 属性 并找出TResult属性和DataTable的列名称相同的属性(PropertyInfo) 并加入到属性列表

Array.ForEach(t.GetProperties(), p => { if (dt.Columns.IndexOf(p.Name) != -1) prlist.Add(p); });

//创建返回的集合

var oblist = new List<TResult>();

foreach (DataRow row in dt.Rows)

{

//创建TResult的实例

var ob = new TResult();

//找到对应的数据 并赋值

prlist.ForEach(p => { if (row[p.Name] != DBNull.Value) p.SetValue(ob, row[p.Name], null); });

//放入到返回的集合中.

oblist.Add(ob);

}

return oblist;

}

}

}

推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
相关阅读
网友关注
最新C#教程学习
热门C#教程学习
编程开发子分类