DataSet 和 List<T> 相互 转换

    /// <summary>  
           /// 实体类转换成DataTable  
           /// 调用示例:DataTable dt= FillDataTable(Entitylist.ToList());  
           /// </summary>  
           /// <param name="modelList">实体类列表</param>  
           /// <returns></returns>  
           public static  DataTable FillDataTable<T>(List<T> modelList)  
           {  
               if (modelList == null || modelList.Count == 0)  
               {  
                   return null;  
               }  
               DataTable dt = CreateData(modelList[0]);//创建表结构  
      
               foreach (T model in modelList)  
               {  
                   DataRow dataRow = dt.NewRow();  
                   foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())  
                   {  
                       dataRow[propertyInfo.Name] = propertyInfo.GetValue(model, null);  
                   }  
                   dt.Rows.Add(dataRow);  
               }  
               return dt;  
           }  
           /// <summary>  
           /// 根据实体类得到表结构  
           /// </summary>  
           /// <param name="model">实体类</param>  
           /// <returns></returns>  
           private static DataTable CreateData<T>(T model)  
           {  
               DataTable dataTable = new DataTable(typeof(T).Name);  
               foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())  
               {  
                   if (propertyInfo.Name != "CTimestamp")//些字段为oracle中的Timesstarmp类型  
                   {  
                       dataTable.Columns.Add(new DataColumn(propertyInfo.Name, propertyInfo.PropertyType));  
                   }  
                   else  
                   {  
                       dataTable.Columns.Add(new DataColumn(propertyInfo.Name, typeof(DateTime)));  
                   }  
               }  
               return dataTable;  
           }  
      
      
            
           /// <summary>  
           /// 将dt转化成Json数据 格式如 table[{id:1,title:'体育'},id:2,title:'娱乐'}]  
           /// </summary>  
           /// <param name="dt"></param>  
           /// <returns></returns>  
           public static string DT2JSON<T>(List<T> dt)  
           {  
               return DT2JSON(dt, 0, "recordcount", "table");  
           }  
           public static string DT2JSON<T>(List<T> dt, int fromCount)  
           {  
               return DT2JSON(dt, fromCount, "recordcount", "table");  
           }  
           /// <summary>  
           /// 将dt转化成Json数据  
           /// </summary>  
           /// <param name="dt"></param>  
           /// <param name="fromCount"></param>  
           /// <param name="totalCountStr"></param>  
           /// <param name="tbname"></param>  
           /// <returns></returns>  
           public static string DT2JSON<T>(List<T> dt, int fromCount, string totalCountStr, string tbname)  
           {  
               return DT2JSON(dt, fromCount, "recordcount", "table", true);  
           }  
           /// <summary>  
           /// 将dt转化成Json数据  
           /// </summary>  
           /// <param name="dt"></param>  
           /// <param name="fromCount"></param>  
           /// <param name="totalCountStr"></param>  
           /// <param name="tbname"></param>  
           /// <returns></returns>  
           public static string DT2JSON<T>(List<T> dt, int fromCount, string totalCountStr, string tbname, bool formatData)  
           {  
               StringBuilder jsonBuilder = new StringBuilder();  
               jsonBuilder.Append(totalCountStr + ":" + dt.Count + "," + tbname + ": [");  
               //T _t = (T)Activator.CreateInstance(typeof(T));  
               //System.Reflection.PropertyInfo[] propertys = _t.GetType().GetProperties();  
               int count2 = 0;  
               foreach (T model in dt)  
               {  
                   if (count2 > 0)  
                       jsonBuilder.Append(",");  
                   jsonBuilder.Append("{");  
                   jsonBuilder.Append("no:" + (fromCount + count2 + 1) + ",");  
                   int count = 0;  
                   foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())  
                   {  
                       if (count > 0)  
                       {  
                           jsonBuilder.Append(",");  
                       }  
                       string temp = string.Empty;  
                       object obj = propertyInfo.GetValue(model, null);  
                       if (obj != null)  
                           temp = obj.ToString();  
                       jsonBuilder.Append(propertyInfo.Name.ToLower() + ": '" +   
                          temp.Replace("\\", "\\\\").Replace("\'", "\\\'").Replace("\t", " ").Replace("\r", " ").Replace("\n", "<br/>") + "'");  
                       count++;  
      
                   }  
                   jsonBuilder.Append("}");  
                   count2++;  
               }  
               jsonBuilder.Append("]");  
               return jsonBuilder.ToString();  
      
           }  
      
      
           /// <summary>  
           /// 将dt转化成Json数据 格式如 table[{id:1,title:'体育'},id:2,title:'娱乐'}]  
           /// </summary>  
           /// <param name="dt"></param>  
           /// <returns></returns>  
           public static string DT2JSON(DataTable dt)  
           {  
               return DT2JSON(dt, 0, "recordcount", "table");  
           }  
           public static string DT2JSON(DataTable dt, int fromCount)  
           {  
               return DT2JSON(dt, fromCount, "recordcount", "table");  
           }  
           /// <summary>  
           /// 将dt转化成Json数据  
           /// </summary>  
           /// <param name="dt"></param>  
           /// <param name="fromCount"></param>  
           /// <param name="totalCountStr"></param>  
           /// <param name="tbname"></param>  
           /// <returns></returns>  
           public static string DT2JSON(DataTable dt, int fromCount, string totalCountStr, string tbname)  
           {  
               return DT2JSON(dt, fromCount, "recordcount", "table", true);  
           }  
           /// <summary>  
           /// 将dt转化成Json数据  
           /// </summary>  
           /// <param name="dt"></param>  
           /// <param name="fromCount"></param>  
           /// <param name="totalCountStr"></param>  
           /// <param name="tbname"></param>  
           /// <returns></returns>  
           public static string DT2JSON(DataTable dt, int fromCount, string totalCountStr, string tbname, bool formatData)  
           {  
               StringBuilder jsonBuilder = new StringBuilder();  
               jsonBuilder.Append(totalCountStr + ":" + dt.Rows.Count + "," + tbname + ": [");  
               for (int i = 0; i < dt.Rows.Count; i++)  
               {  
                   if (i > 0)  
                       jsonBuilder.Append(",");  
                   jsonBuilder.Append("{");  
                   jsonBuilder.Append("no:" + (fromCount + i + 1) + ",");  
                   for (int j = 0; j < dt.Columns.Count; j++)  
                   {  
                       if (j > 0)  
                           jsonBuilder.Append(",");  
      
                       jsonBuilder.Append(dt.Columns[j].ColumnName.ToLower() + ": '" + dt.Rows[i][j].ToString().Replace("\\", "\\\\").Replace("\'", "\\\'").Replace("\t", " ").Replace("\r", " ").Replace("\n", "<br/>") + "'");  
                   }  
                   jsonBuilder.Append("}");  
               }  
               jsonBuilder.Append("]");  
               return jsonBuilder.ToString();  
      
           }  
           /// <summary>  
           /// 将DataTable转换为list  
           /// </summary>  
           /// <typeparam name="T"></typeparam>  
           /// <param name="dt"></param>  
           /// <returns></returns>  
           public static List<T> DT2List<T>(DataTable dt)  
           {  
               if (dt == null)  
                   return null;  
               List<T> result = new List<T>();  
               for (int j = 0; j < dt.Rows.Count; j++)  
               {  
                   T _t = (T)Activator.CreateInstance(typeof(T));  
                   System.Reflection.PropertyInfo[] propertys = _t.GetType().GetProperties();  
                   foreach (System.Reflection.PropertyInfo pi in propertys)  
                   {  
                       for (int i = 0; i < dt.Columns.Count; i++)  
                       {  
                           // 属性与字段名称一致的进行赋值   
                           if (pi.Name.ToLower().Equals(dt.Columns[i].ColumnName.ToLower()))  
                           {  
                               if (dt.Rows[j][i] != DBNull.Value)  
                               {  
                                   if (pi.PropertyType.ToString() == "System.Int32")  
                                   {  
                                       pi.SetValue(_t, Int32.Parse(dt.Rows[j][i].ToString()), null);  
                                   }  
                                   if (pi.PropertyType.ToString() == "System.DateTime")  
                                   {  
                                       pi.SetValue(_t, Convert.ToDateTime(dt.Rows[j][i].ToString()), null);  
                                   }  
                                   if (pi.PropertyType.ToString() == "System.String")  
                                   {  
                                       pi.SetValue(_t, dt.Rows[j][i].ToString(), null);  
                                   }  
                                   if (pi.PropertyType.ToString() == "System.Boolean")  
                                   {  
                                       pi.SetValue(_t, Convert.ToBoolean(dt.Rows[j][i].ToString()), null);  
                                   }  
                               }  
                               else  
                                   pi.SetValue(_t, "", null);//为空,但不为Null  
                               break;  
                           }  
                       }  
                   }  
                   result.Add(_t);  
               }  
               return result;  
           }  

 

转载于:https://www.cnblogs.com/8090sns/archive/2012/12/21/datatable.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值