DataTable 转换为List 集合

		/// <summary>
		/// DataTable转List<T>
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="dt"></param>
		/// <returns></returns>
		public static List<T> toList<T>(this DataTable dt) where T: class, new()
        {
			var prList = new List<PropertyInfo>();
			var t = typeof(T);

			Array.ForEach(t.GetProperties(), p =>
			{
				if(dt.Columns.IndexOf(p.Name) != -1)
                {
					prList.Add(p);
                }
			});

			var ret = new List<T>();
			foreach(DataRow dr in dt.Rows)
            {
				var item = new T();
				prList.ForEach(p =>
				{
					if (dr[p.Name] != DBNull.Value)
					{
						p.SetValue(item, dr[p.Name], null);
					}
				});

				ret.Add(item);
            }

			return ret;
        }

  以上为扩展函数,怎么调用相信你懂的!!

posted on 2022-09-07 22:17  清清飞扬  阅读(8)  评论(0编辑  收藏  举报