日期:2014-05-17  浏览次数:20850 次

如何将DataTable转换为list?
想写一个方法 传入任何DataTable都转换为List<> 每一条记录为一个对象 存入list中   类似linq里那种   求思路~

------解决方案--------------------
http://www.cnblogs.com/chenliang0724/archive/2009/05/20/1471780.html
------解决方案--------------------

public static IList<T> ConvertToModel(DataTable dt)
  {
  // 定义集合
  IList<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;

  // 检查DataTable是否包含此列
  if (dt.Columns.Contains(tempName))
  {
  // 判断此属性是否有Setter
  if (!pi.CanWrite) continue;

  object value = dr[tempName];
  if (value != DBNull.Value)
  pi.SetValue(t, value, null);
  }
  }

  ts.Add(t);
  }

  return ts;

  }



------解决方案--------------------
楼上的方法需要放在一个带有new()约束的类里
或者方法签名改成这样
public static IList<T> ConvertToModel<T>(DataTable dt) where T : new()
{    
}
------解决方案--------------------
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;

namespace ssss

  /// <summary>
  /// Summary description for ConvertEntity1
  /// </summary>
  public static class IDataReaderExt