DataTable转List

Invoke : DataTableToList<City>.ConvertToModel(ds.Tables[0]).ToList<City>();

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Web;

namespace JsonDataInMVC.DBOperator
{
 public static class DataTableToList<T> where T : new()
 {
 public static IList<T> ConvertToModel(DataTable dt)
 {
 //定义集合
 IList<T> ts = new List<T>();
 T t = new T();
 string tempName = "";
 //获取此模型的公共属性
 PropertyInfo[] propertys = t.GetType().GetProperties();
 foreach (DataRow row in dt.Rows)
 {
 t = new T();
 foreach (PropertyInfo pi in propertys)
 {
  tempName = pi.Name;
  //检查DataTable是否包含此列
  if (dt.Columns.Contains(tempName))
  {
  //判断此属性是否有set
  if (!pi.CanWrite)
  continue;
  object value = row[tempName];
  if (value != DBNull.Value)
  pi.SetValue(t, value, null);
  }
 }
 ts.Add(t);
 }
 return ts;
 }
 }
} 

转载于:https://www.cnblogs.com/zhangchenliang/p/6255255.html

猜你喜欢

转载自blog.csdn.net/weixin_33778778/article/details/93495571