Jason实现DataTable和List互转

        /// <summary>
        /// 转换List到DataTable
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public DataTable GenericToDataTable<T>(IList<T> list)
        {
            var json = JsonConvert.SerializeObject(list);
            DataTable dt = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable)));
            return dt;
        }

        /// <summary>
        /// 转换DataTable到List
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public IList<T> DataTableToGeneric<T>(DataTable dt)
        {
            var json = JsonConvert.SerializeObject(dt);
            IList<T> list = JsonConvert.DeserializeObject<IList<T>>(json);
            return list;
        }

  

posted @ 2020-12-25 14:23  南秦岭  阅读(125)  评论(0编辑  收藏  举报