首页 > 编程语言 >C#DataTable(转List /JSON/字典 互转)【工具类】

C#DataTable(转List /JSON/字典 互转)【工具类】

时间:2022-10-19 11:02:27浏览次数:56  
标签:C# List Add foreach 互转 new dt DataTable

#region  数据表DataTable 转键值对集合 List
        /// <summary>
        /// 数据表DataTable 转键值对集合 List
        /// 把DataTable转成 List集合, 存每一行
        /// 集合中放的是键值对字典,存每一列
        /// </summary>
        /// <param name="dt">数据表</param>
        /// <returns>哈希表数组</returns>
        public static List<Dictionary<string, object>> DataTableToList(DataTable dt)
        {
            List<Dictionary<string, object>> list= new List<Dictionary<string, object>>();
            foreach (DataRow dr in dt.Rows)
            {
                Dictionary<string, object> dic = new Dictionary<string, object>();
                foreach (DataColumn dc in dt.Columns)
                {
                    dic.Add(dc.ColumnName, dr[dc.ColumnName]);
                }
                list.Add(dic);
            }
            return list;
        }
        #endregion

        #region 数据集转键值对数组字典

        /// <summary>
        /// 数据集转键值对数组字典
        /// </summary>
        /// <param name="dataSet">数据集</param>
        /// <returns>键值对数组字典</returns>
        public static Dictionary<string, List<Dictionary<string, object>>> DataSetToDic(DataSet ds)
        {
            Dictionary<string, List<Dictionary<string, object>>> result = new Dictionary<string, List<Dictionary<string, object>>>();
            foreach (DataTable dt in ds.Tables)
                result.Add(dt.TableName, DataTableToList(dt));
            return result;
        }
        #endregion

        #region 数据表Tables 转JSON
        /// <summary>
        /// 数据表转Tables JSON
        /// </summary>
        /// <param name="dataTable">数据表</param>
        /// <returns>JSON字符串</returns>
        public static string DataTableToJSON(DataTable dt)
        {
            return JsonHelper.ObjectToJSON(DataTableToList(dt));
        }
        #endregion

        #region 将datatable转换为json
        /// <summary>
        /// 将datatable转换为json
        /// </summary>
        /// <param name="dtb">Dt</param>
        /// <returns>JSON字符串</returns>
        public static string Dtb2Json(DataTable dtb)
        {
            System.Collections.ArrayList dic = new System.Collections.ArrayList();
            foreach (DataRow dr in dtb.Rows)
            {
                System.Collections.Generic.Dictionary<string, object> drow = new System.Collections.Generic.Dictionary<string, object>();
                foreach (DataColumn dc in dtb.Columns)
                {
                    drow.Add(dc.ColumnName, dr[dc.ColumnName]);
                }

                dic.Add(drow);
            }
            return null;
        }
        #endregion

        #region 将Dictionary转换为数据表数据 Tables
        public static DataTable DictToDataTable(Dictionary<string, object> dict)
        {
            DataTable dt = new DataTable();
            foreach (var colName in dict.Keys)
            {
                dt.Columns.Add(colName, typeof(string));
            }
            DataRow dr = dt.NewRow();
            foreach (KeyValuePair<string, object> item in dict)
            {
                dr[item.Key] = item.Value;
            }
            dt.Rows.Add(dr);
            return dt;
        }
        #endregion

        #region 将List转换为数据表数据 Tables
        /// <summary>
        /// List转DataTable
        /// </summary>
        public static DataTable ListToDataTable<T>(List<T> list)
        {
            if (list == null || list.Count == 0)
            {
                return new DataTable();
            }
            //获取T下所有的属性
            Type entityType = list[0].GetType();
            PropertyInfo[] entityProperties = entityType.GetProperties();
            DataTable dt = new DataTable("data");
            for (int i = 0; i < entityProperties.Length; i++)
            {
                dt.Columns.Add(entityProperties[i].Name);
            }
            foreach (var item in list)
            {
                if (item.GetType() != entityType)
                {
                    throw new Exception("要转换集合元素类型不一致!");
                }
                //创建一个用于放所有属性值的数组
                object[] entityValues = new object[entityProperties.Length];
                for (int i = 0; i < entityProperties.Length; i++)
                {
                    entityValues[i] = entityProperties[i].GetValue(item, null);
                }
                dt.Rows.Add(entityValues);
            }
            return dt;
        }
        #endregion

        #region  Json 字符串 转换为 DataTable数据集合  简要版,正在使用中
        /// <summary>
        /// Json 字符串 转换为 DataTable数据集合  简要版,正在使用中
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        ///
        //格式;
        //[{"mac":"20:f1:7c:c5:cd:80","rssi":"-86","ch":"9"},{"mac":"20:f1:7c:c5:cd:85","rssi":"-91","ch":"9"}]
        public static DataTable ToDataTableTwo(string json)
        {
            DataTable dataTable = new DataTable();  //实例化
            DataTable result;
            try
            {
                List<Dictionary<string, object>> arrayList = JsonHelper.JSONToObject<List<Dictionary<string, object>>>(json);
                if (arrayList != null && arrayList.Count > 0)
                {
                    foreach (Dictionary<string, object> dictionary in arrayList)
                    {
                        if (dictionary.Keys.Count == 0)
                        {
                            result = dataTable;
                            return result;
                        }
                        if (dataTable.Columns.Count == 0)
                        {
                            foreach (var current in dictionary)
                            {
                                if (current.Value != null)
                                {
                                    dataTable.Columns.Add(current.Key, current.Value.GetType());
                                }
                                else
                                {
                                    dataTable.Columns.Add(current.Key);
                                }
                            }
                        }
                        DataRow dataRow = dataTable.NewRow();
                        foreach (string current in dictionary.Keys)
                        {
                            if (dictionary[current] != null)
                            {
                                dataRow[current] = dictionary[current];
                            }
                        }
                        dataTable.Rows.Add(dataRow); //循环添加行到DataTable中
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            result = dataTable;
            return result;
        }
        #endregion

  

标签:C#,List,Add,foreach,互转,new,dt,DataTable
From: https://www.cnblogs.com/hapgaoyi/p/16805468.html

相关文章

  • IEC发布自动电气控制标准
    2022年9月19日,国际电工委员会(IEC)发布标准IEC60730-1:2022《自动电气控制-第1部分:通用要求》,IEC60703-1:2022标准适用于在家用器具和类似用途的设备内、设备上使用,或与之......
  • go 和 elixir 的 grpc 通信
    步骤准备安装protoc-gen-elixirmixescript.installhexprotobuf具体步骤创建项目mixnewappdemo编写pb文件helloword.protosyntax="proto3";optionj......
  • CPU host-passthrough技术与应用
    为了保证虚拟机在不同宿主机之间迁移的时候的兼容性,Libvirt对CPU提炼出标准的几种类型,在/usr/share/libvirt/cpu_map.xml中可以查到。cpu_map.xml不仅是CPU型号,还有生产商......
  • DSC集群搭建
    一、集群介绍  DMDSC集群是一个多实例、单数据库的系统。多个数据库实例可以同时访问、修改同一个数据库的数据。用户可以登录集群中的任意一个数据库实例,获得完整的数......
  • JDBCTemplate-执行DML语句、执行DQL语句
    JDBCTemplate-执行DML语句   publicclassEmp{privateintid;privateStringename;privateintjob_id;privateintmgr;privateD......
  • Windows使用Docker出现exit 139错误
    使用DockerDesktop启动一个镜像以后,发现直接EXITED(139)这时候用dockerlogcontainerId也获取不到任何日志问题缘由找了比较多的资料哈,Centos6下对Docker支持确实......
  • docker使用-01镜像管理
    安装dockerhttps://dockerdocs.cn/get-docker/构建第一个镜像1.创建flask应用fromflaskimportFlaskapp=Flask(__name__)@app.route('/')deftest():re......
  • ‘project JDK is not define‘ 解决方案 打开【File - Project Structure】 修改【M
    ‘projectJDKisnotdefine‘解决方案最近想玩玩javap反编译然后捣鼓来捣鼓去,出现了这个问题,解决方案之一1.打开【File-ProjectStructure】2.修改【Module......
  • 提高编程效率的5大VS Code插件
    前言作为一名开发人员,大家会一直寻找可以帮助改进日常工作流程的解决方案,VSCode市场中就有很多优秀的扩展插件程序。正文​​一、GitLive​​GitLive是一个出色的扩展程......
  • Xdocreport 生成docx文件 (二)
    基于 Xdocreport生成docx文件(一)  对文件中添加一张可以替换的图片插入一个图片,选中图片,插入=>书签=>添加img  代码:1publicstaticvoidmain(Str......