在云那方

首页 新随笔 联系 订阅 管理
/// <summary>
        /// DataTable转List
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static List<T> ToList<T>(this DataTable dt) where T : new()
        {
            List<T> list = new List<T>();

            var propertylist = typeof(T).GetProperties();

            foreach (DataRow row in dt.Rows)
            {
                T t = new T();
                foreach (PropertyInfo property in propertylist)
                {
                    foreach (DataColumn column in dt.Columns)
                    {
                        if (property.Name.ToLower() == column.ColumnName.ToLower())
                        {
                            var value = row[column.ColumnName];
                            if (value != DBNull.Value)
                                property.SetValue(t, value, null);
                        }
                    }
                }

                list.Add(t);
            }

            return list;
        }

 

posted on 2012-07-04 00:34  Rich.T  阅读(1571)  评论(0编辑  收藏  举报