[C#]把DataTable转换成泛型实体List

public class BaseBLL
{
    /// <summary>
    /// 把DataTable转换成泛型实体List
    /// </summary>
    /// <typeparam name="T">泛型实体</typeparam>
    /// <param name="dt">DataTable数据</param>
    /// <returns>泛型实体List</returns>
    protected IList<T> GetSingleList<T>(DataTable dt)
    {
        List<T> list = new List<T>();
        Type type = typeof(T);
        foreach (DataRow row in dt.Rows)
        {
            T t = Activator.CreateInstance<T>();
            foreach (DataColumn conl in dt.Columns)
            {
                System.Reflection.PropertyInfo pro = t.GetType().GetProperty(conl.ColumnName);
                if (pro != null && pro.CanWrite && row[conl.ColumnName].GetType() != typeof(DBNull))
                {
                    pro.SetValue(t, row[conl.ColumnName], null);
                }
            }
            list.Add(t);
        }
        return list;
    }
}

posted @ 2012-07-18 16:37  Hsppl  阅读(353)  评论(0编辑  收藏  举报