码迷,mamicode.com
首页 > 其他好文 > 详细

Datatable与实体list之间的转换

时间:2015-01-29 07:05:40      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:

public static class ConvertDataTableWithList<T> where T:new()
    {
        public static List<T> ConvertToModelList(DataTable dt)
        {
            //定义集合
            List<T> ts = new List<T>();
            T t = new T();
            //获取此模型的公共属性
            PropertyInfo[] propertys = t.GetType().GetProperties();
            foreach (DataRow row in dt.Rows)
            {
                t = new T();
                foreach (PropertyInfo pi in propertys)
                {
                    //检查DataTable是否包含此列
                    if (dt.Columns.Contains(pi.Name))
                    {
                        //判断此属性是否有set
                        if (!pi.CanWrite)
                            continue;
                        object value = row[pi.Name];
                        if (value != DBNull.Value)
                            pi.SetValue(t, value, null);
                    }
                }
                ts.Add(t);
            }
            return ts;
        }
        public static DataTable ConvertToDataTable(List<T> list)
        {
            DataTable dt=new DataTable();
           
            T t=new T();
            PropertyInfo [] propertys=t.GetType().GetProperties();
            //给datatable添加列
            foreach (PropertyInfo pi in propertys)
            {
                dt.Columns.Add(pi.Name);
            }
            dt.AcceptChanges();
            foreach (T item in list)
            {
                t = new T();
                DataRow dr = dt.NewRow();
                foreach (PropertyInfo pi in propertys)
                {
                    if (!pi.CanWrite)
                        continue;
                    dr[pi.Name] = pi.GetValue(t);
                }
                dt.Rows.Add(dr);
            }
            dt.AcceptChanges();
            return dt;
        }
    }

Datatable与实体list之间的转换

标签:

原文地址:http://www.cnblogs.com/lvdong-1986/p/4257748.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!