DataTable到实体类的转换

    搞软件差不多的都知道,经常用到DataTable到实体类的转换,常用的就是利用列名或索引一列一列给实体赋值,如果列少还行,列多的话,真是烦死人,而且容易出错.偶也常被困扰.早就写这样的方法.却一直没有时间,前几天忙里偷闲,参考一些资料,改编了别人的一些方法,现分享如下:

    1.DataTable到List<T>的转换

          public static List<T> DataTableToT<T>(DataTable source) where T : class, new()
          {
            List<T> itemlist = null;
            if (source == null || source.Rows.Count == 0)
            {
                return itemlist;
            }
            itemlist = new List<T>();
            T item = null;
            Type targettype = typeof(T);
            Type ptype = null;
            Object value = null;
            foreach (DataRow dr in source.Rows)
            {
                item = new T();
                foreach (PropertyInfo pi in targettype.GetProperties())
                {
                    if (pi.CanWrite && source.Columns.Contains(pi.Name))
                    {
                        ptype = Type.GetType(pi.PropertyType.FullName);
                        value = Convert.ChangeType(dr[pi.Name], ptype);
                        pi.SetValue(item, value, null);
                    }
                }
                itemlist.Add(item);
            }

            return itemlist;
         }
    2.DataRow到T的转换

       public static T DataRowToT<T>(DataRow source) where T:class,new()
        {
            T item = null;
            if (source == null)
            {
                return item;
            }
            item = new T();
            Type targettype = typeof(T);
            Type ptype = null;
            Object value = null;
           
            foreach (PropertyInfo pi in targettype.GetProperties())
            {
                if (pi.CanWrite && source.Table.Columns.Contains(pi.Name))
                {
                    ptype = Type.GetType(pi.PropertyType.FullName);
                    value = Convert.ChangeType(source[pi.Name], ptype);
                    pi.SetValue(item, value, null);
                }
            }
            return item;
        }

   备注:1.里面用到了反射与泛型,而且都是最入门级的.不再做详解

posted @ 2011-09-28 09:55  --中庸--  阅读(2537)  评论(2编辑  收藏  举报