手机
当前位置:查字典教程网 >编程开发 >C#教程 >c#的datatable转list示例
c#的datatable转list示例
摘要:复制代码代码如下: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#的datatable转list示例】相关文章:

c#读取xml文件到datagridview实例

C#简单的加密类实例

c#剪切板操作的简单实例

C#实现协同过滤算法的实例代码

C#独立域名查询代码

C#位移的介绍与例子

c#中的interface abstract与virtual介绍

C#中方法的详细介绍

C#.net中的类型转换详细介绍

C# DataTable的详细用法分享

精品推荐
分类导航