首页 > 其他 > 详细

DataTable转List

时间:2016-04-21 18:17:30      阅读:118      评论:0      收藏:0      [点我收藏+]
 public class ModelConvertHelper<T> where T : new()  // 此处一定要加上new()
        {

            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;
            }
        }
调用方法为: List<NewsInfo> list = ModelConvertHelper<NewsInfo>.ConvertToModel(da);

  

DataTable转List

原文:http://www.cnblogs.com/qzxj/p/5417983.html

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