路漫漫,求索不息

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

public static T GetEntity<T>(DataTable table) where T : new()
    {
        T entity = new T();
        foreach (DataRow row in table.Rows)
        {
            foreach (var item in entity.GetType().GetProperties())
            {
                if (row.Table.Columns.Contains(item.Name))
                {
                    if (DBNull.Value != row[item.Name])
                    {
                        item.SetValue(entity, Convert.ChangeType(row[item.Name], item.PropertyType), null);
                    }

                }
            }
        }

        return entity;
    }

 

dataTable转化为实体列表MethodOne:

    public static IList<T> GetEntities<T>(DataTable table) where T : new()
    {
        IList<T> entities = new List<T>();
        foreach (DataRow row in table.Rows)
        {
            T entity = new T();
            foreach (var item in entity.GetType().GetProperties())
            {
                item.SetValue(entity, Convert.ChangeType(row[item.Name], item.PropertyType), null);
            }
            entities.Add(entity);
        }
        return entities;
    }

MethodTwo:

 /// <summary>
        /// DataTable 转化为对象集合
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static List<TEntity> ToList<TEntity>(DataTable dt) where TEntity : new()
        {
            List<TEntity> listEntity = new List<TEntity>();
            if (dt != null && dt.Rows.Count > 0)
            {
                int fieldCount = dt.Columns.Count;
                foreach (DataRow item in dt.Rows)
                {
                    TEntity t = (TEntity)Activator.CreateInstance(typeof(TEntity));

                    for (int i = 0; i < fieldCount; i++)
                    {
                        PropertyInfo field = t.GetType().GetProperty(dt.Columns[i].ColumnName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
                        if (field != null)
                        {
                            if (item[i] == null || Convert.IsDBNull(item[i]))
                            {
                                field.SetValue(t, null, null);
                            }
                            else
                            {
                                field.SetValue(t, item[i], null);
                            }
                        }
                    }

                    listEntity.Add(t);
                }
            }
            if (listEntity.Count == 0)
            {
                return null;
            }

            return listEntity;
        }

posted on 2013-09-02 20:23  路漫漫,求索不息  阅读(440)  评论(0编辑  收藏  举报