欢迎光临
我的个人博客网站

C#DataTable(转List /JSON/字典 互转)

  1    #region  数据表DataTable 转键值对集合 List   2         /// <summary>    3         /// 数据表DataTable 转键值对集合 List   4         /// 把DataTable转成 List集合, 存每一行    5         /// 集合中放的是键值对字典,存每一列    6         /// </summary>    7         /// <param name="dt">数据表</param>    8         /// <returns>哈希表数组</returns>    9         public static List<Dictionary<string, object>> DataTableToList(DataTable dt)  10         {  11             List<Dictionary<string, object>> list  12                  = new List<Dictionary<string, object>>();  13   14             foreach (DataRow dr in dt.Rows)  15             {  16                 Dictionary<string, object> dic = new Dictionary<string, object>();  17                 foreach (DataColumn dc in dt.Columns)  18                 {  19                     dic.Add(dc.ColumnName, dr[dc.ColumnName]);  20                 }  21                 list.Add(dic);  22             }  23             return list;  24         }  25         #endregion  26   27         #region 数据集转键值对数组字典  28   29         /// <summary>   30         /// 数据集转键值对数组字典   31         /// </summary>   32         /// <param name="dataSet">数据集</param>   33         /// <returns>键值对数组字典</returns>   34         public static Dictionary<string, List<Dictionary<string, object>>> DataSetToDic(DataSet ds)  35         {  36             Dictionary<string, List<Dictionary<string, object>>> result = new Dictionary<string, List<Dictionary<string, object>>>();  37   38             foreach (DataTable dt in ds.Tables)  39                 result.Add(dt.TableName, DataTableToList(dt));  40   41             return result;  42         }  43         #endregion  44   45         #region 数据表Tables 转JSON  46         /// <summary>   47         /// 数据表转Tables JSON   48         /// </summary>   49         /// <param name="dataTable">数据表</param>   50         /// <returns>JSON字符串</returns>   51         public static string DataTableToJSON(DataTable dt)  52         {  53             return JsonHelper.ObjectToJSON(DataTableToList(dt));  54         }  55         #endregion  56   57         #region 将datatable转换为json  58         /// <summary>  59         /// 将datatable转换为json    60         /// </summary>  61         /// <param name="dtb">Dt</param>  62         /// <returns>JSON字符串</returns>  63         public static string Dtb2Json(DataTable dtb)  64         {  65             //JavaScriptSerializer jss = new JavaScriptSerializer();  66   67             System.Collections.ArrayList dic = new System.Collections.ArrayList();  68   69             foreach (DataRow dr in dtb.Rows)  70             {  71                 System.Collections.Generic.Dictionary<string, object> drow = new System.Collections.Generic.Dictionary<string, object>();  72   73                 foreach (DataColumn dc in dtb.Columns)  74                 {  75                     drow.Add(dc.ColumnName, dr[dc.ColumnName]);  76                 }  77   78                 dic.Add(drow);  79             }  80   81             return null;  82         }  83         #endregion  84   85         #region 将Dictionary转换为数据表数据 Tables  86         public static DataTable DictToDataTable(Dictionary<string, object> dict)  87         {  88             DataTable dt = new DataTable();  89   90             //dt.Columns.Add("ID", typeof(Guid));  91             //dt.Columns.Add("DID", typeof(string));  92             //dt.Columns.Add("DEPARTMENTNUM", typeof(string));  93             //dt.Columns.Add("DEPARTMENTNAME", typeof(string));  94             //dt.Columns.Add("REMARKS", typeof(string));  95   96             foreach (var colName in dict.Keys)  97             {  98                 dt.Columns.Add(colName, typeof(string));  99             } 100             DataRow dr = dt.NewRow(); 101             foreach (KeyValuePair<string, object> item in dict) 102             { 103                 dr[item.Key] = item.Value; 104             } 105             dt.Rows.Add(dr); 106             return dt; 107         } 108         #endregion 109  110         #region 将List转换为数据表数据 Tables 111         /// <summary> 112         /// List转DataTable 113         /// </summary> 114         public static DataTable ListToDataTable<T>(List<T> list) 115         { 116             if (list == null || list.Count == 0) 117             { 118                 return new DataTable(); 119             } 120  121             //获取T下所有的属性 122             Type entityType = list[0].GetType(); 123             PropertyInfo[] entityProperties = entityType.GetProperties(); 124  125             DataTable dt = new DataTable("data"); 126  127             for (int i = 0; i < entityProperties.Length; i++) 128             { 129                 dt.Columns.Add(entityProperties[i].Name); 130             } 131  132             foreach (var item in list) 133             { 134                 if (item.GetType() != entityType) 135                 { 136                     throw new Exception("要转换集合元素类型不一致!"); 137                 } 138                 //创建一个用于放所有属性值的数组 139                 object[] entityValues = new object[entityProperties.Length]; 140                 for (int i = 0; i < entityProperties.Length; i++) 141                 { 142                     entityValues[i] = entityProperties[i].GetValue(item, null); 143                 } 144  145                 dt.Rows.Add(entityValues); 146             } 147             return dt; 148         } 149         #endregion 150  151         #region  Json 字符串 转换为 DataTable数据集合  简要版,正在使用中 152         /// <summary> 153         /// Json 字符串 转换为 DataTable数据集合  简要版,正在使用中 154         /// </summary> 155         /// <param name="json"></param> 156         /// <returns></returns> 157         ///  158         //格式; 159         //[{"mac":"20:f1:7c:c5:cd:80","rssi":"-86","ch":"9"},{"mac":"20:f1:7c:c5:cd:85","rssi":"-91","ch":"9"}] 160         public static DataTable ToDataTableTwo(string json) 161         { 162             DataTable dataTable = new DataTable();  //实例化 163             DataTable result; 164             try 165             { 166                 List<Dictionary<string, object>> arrayList = JsonHelper.JSONToObject<List<Dictionary<string, object>>>(json); 167  168                 if (arrayList != null && arrayList.Count > 0) 169                 { 170                     foreach (Dictionary<string, object> dictionary in arrayList) 171                     { 172                         if (dictionary.Keys.Count == 0) 173                         { 174                             result = dataTable; 175                             return result; 176                         } 177  178                         //Columns 179                         if (dataTable.Columns.Count == 0) 180                         { 181                             foreach (var current in dictionary) 182                             { 183                                 if (current.Value != null) 184                                 { 185                                     dataTable.Columns.Add(current.Key, current.Value.GetType()); 186                                 } 187                                 else 188                                 { 189                                     dataTable.Columns.Add(current.Key); 190                                 } 191                             } 192                         } 193  194                         //Rows 195                         DataRow dataRow = dataTable.NewRow(); 196  197                         foreach (string current in dictionary.Keys) 198                         { 199                             if (dictionary[current] != null) 200                             { 201                                 dataRow[current] = dictionary[current]; 202                             } 203                         } 204  205                         dataTable.Rows.Add(dataRow); //循环添加行到DataTable中 206                     } 207                 } 208             } 209             catch (Exception ex) 210             { 211                 throw ex; 212             } 213  214             result = dataTable; 215             return result; 216         } 217         #endregion

 

赞(0) 打赏
未经允许不得转载:张拓的天空 » C#DataTable(转List /JSON/字典 互转)
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

专业的IT技术经验分享 更专业 更方便

联系我们本站主机

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏