首页 > 其他 > 详细

DataTable转换成List

时间:2017-07-05 15:45:45      阅读:371      评论:0      收藏:0      [点我收藏+]

 

using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using System.Text;

 

public class Helper<T> where T : new()
{
/// <summary>
/// datatable转list
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static List<T> ConvertToModel(DataTable dt)
{

List<T> ts = new List<T>();// 定义集合
Type type = typeof(T); // 获得此模型的类型
string tempName = "";
foreach (DataRow dr in dt.Rows)
{
T t = new T();
PropertyInfo[] propertys = t.GetType().GetProperties();// 获得此模型的公共属性
foreach (PropertyInfo pi in propertys)
{
tempName = pi.Name;
if (dt.Columns.Contains(tempName))
{
if (!pi.CanWrite) continue;
object value = dr[tempName];
if (value != DBNull.Value)
pi.SetValue(t, value, null);
}
}
ts.Add(t);
}
return ts;
}


}

DataTable转换成List

原文:http://www.cnblogs.com/2260827114com/p/7121740.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!