DataTableList

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Data;  
  6. using System.Collections;  
  7. using System.Reflection;  
  8. namespace DatableToList  
  9. {  
  10.     class ConvertHelper<T> where T : new()  
  11.     {  
  12.         /// <summary>  
  13.         /// 利用反射和泛型  
  14.         /// </summary>  
  15.         /// <param name="dt"></param>  
  16.         /// <returns></returns>  
  17.         public static List<T> ConvertToList(DataTable dt)  
  18.         {  
  19.   
  20.             // 定義集合  
  21.             List<T> ts = new List<T>();  
  22.   
  23.             // 獲得此模型的類型  
  24.             Type type = typeof(T);  
  25.             //定義一個臨時變量  
  26.             string tempName = string.Empty;  
  27.             //遍歷DataTable中所有的數據行  
  28.             foreach (DataRow dr in dt.Rows)  
  29.             {  
  30.                 T t = new T();  
  31.                 // 獲得此模型的公共屬性  
  32.                 PropertyInfo[] propertys = t.GetType().GetProperties();  
  33.                 //遍歷該對象的所有屬性  
  34.                 foreach (PropertyInfo pi in propertys)  
  35.                 {  
  36.                     tempName = pi.Name;//將屬性名稱賦值給臨時變量  
  37.                     //檢查DataTable是否包含此列(列名==對象的屬性名)    
  38.                     if (dt.Columns.Contains(tempName))  
  39.                     {  
  40.                         // 判斷此屬性是否有Setter  
  41.                         if (!pi.CanWrite) continue;//該屬性不可寫,直接跳出  
  42.                         //取值  
  43.                         object value = dr[tempName];  
  44.                         //如果非空,則賦給對象的屬性  
  45.                         if (value != DBNull.Value)  
  46.                             pi.SetValue(t, value, null);  
  47.                     }  
  48.                 }  
  49.                 //對象添加到泛型集合中  
  50.                 ts.Add(t);  
  51.             }  
  52.   
  53.             return ts;  
  54.   
  55.         }  
  56.     }  
  57. }  



/// <summary>
        /// 將集合類轉換成DataTable
        /// </summary>
        /// <param name="list">集合</param>
        /// <returns></returns>
        public static DataTable ToDataTable(IList list)
        {
            DataTable result = new DataTable();
            if (list.Count > 0)
            {
                PropertyInfo[] propertys = list[0].GetType().GetProperties();
                foreach (PropertyInfo pi in propertys)
                {
                    result.Columns.Add(pi.Name, pi.PropertyType);
                }
                for (int i = 0; i < list.Count; i++)
                {
                    ArrayList tempList = new ArrayList();
                    foreach (PropertyInfo pi in propertys)
                    {
                        object obj = pi.GetValue(list[i], null);
                        tempList.Add(obj);
                    }
                    object[] array = tempList.ToArray();
                    result.LoadDataRow(array, true);
                }
            }
            return result;
        }
        /// <summary>
        /// 將泛型集合類轉換成DataTable
        /// </summary>
        /// <typeparam name="T">集合項類型</typeparam>
        /// <param name="list">集合</param>
        /// <returns>數據集(表)</returns>
        public static DataTable ToDataTable<T>(IList<T> list)
        {
            return ConvertX.ToDataTable<T>(list, null);
        }
        /// <summary>
        /// 將泛型集合類轉換成DataTable
        /// </summary>
        /// <typeparam name="T">集合項類型</typeparam>
        /// <param name="list">集合</param>
        /// <param name="propertyName">需要返回的列的列名</param>
        /// <returns>數據集(表)</returns>
        public static DataTable ToDataTable<T>(IList<T> list, params string[] propertyName)
        {
            List<string> propertyNameList = new List<string>();
            if (propertyName != null)
                propertyNameList.AddRange(propertyName);
            DataTable result = new DataTable();
            if (list.Count > 0)
            {
                PropertyInfo[] propertys = list[0].GetType().GetProperties();
                foreach (PropertyInfo pi in propertys)
                {
                    if (propertyNameList.Count == 0)
                    {
                        result.Columns.Add(pi.Name, pi.PropertyType);
                    }
                    else 
                    {
                        if (propertyNameList.Contains(pi.Name))
                            result.Columns.Add(pi.Name, pi.PropertyType);
                    }
                }
                for (int i = 0; i < list.Count; i++)
                {
                    ArrayList tempList = new ArrayList();
                    foreach (PropertyInfo pi in propertys)
                    {
                        if (propertyNameList.Count == 0)
                        {
                            object obj = pi.GetValue(list[i], null);
                            tempList.Add(obj);
                        }
                        else
                        {
                            if (propertyNameList.Contains(pi.Name))
                            {
                                object obj = pi.GetValue(list[i], null);
                                tempList.Add(obj);
                            }
                        }
                    }
                    object[] array = tempList.ToArray();
                    result.LoadDataRow(array, true);
                }
            }
            return result;
        }






List<T>轉Json

        public static string Obj2Json<T>(T data)
        {
            try
            {
                System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(data.GetType());
                using (MemoryStream ms = new MemoryStream())
                {
                    serializer.WriteObject(ms, data);
                    return Encoding.UTF8.GetString(ms.ToArray());
                }
            }
            catch
            {
                return null;
            }
        }

Json轉List<T>

        public static Object Json2Obj(String json,Type t)
        {
            try
            {
                System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(t);
                using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
                {
                   
                    return  serializer.ReadObject(ms);
                }
            }
            catch
            {
                return null;
            }
        }
 

DataTable 轉Json

        public static string DataTable2Json(DataTable dt)
        {
            if (dt.Rows.Count == 0)
            {
                return "";
            }

            StringBuilder jsonBuilder = new StringBuilder();
            // jsonBuilder.Append("{"); 
            //jsonBuilder.Append(dt.TableName.ToString());  
            jsonBuilder.Append("[");//轉換成多個model的形式
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                jsonBuilder.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    jsonBuilder.Append("\"");
                    jsonBuilder.Append(dt.Columns[j].ColumnName);
                    jsonBuilder.Append("\":\"");
                    jsonBuilder.Append(dt.Rows[i][j].ToString());
                    jsonBuilder.Append("\",");
                }
                jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                jsonBuilder.Append("},");
            }
            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            jsonBuilder.Append("]");
            //  jsonBuilder.Append("}");
            return jsonBuilder.ToString();
        }

單個對象轉JSON

 

        public static T Json2Obj<T>(string json) 
        {
            T obj = Activator.CreateInstance<T>();
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(json)))
            {
                System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
                return (T)serializer.ReadObject(ms);
            }
        }

發佈了29 篇原創文章 · 獲贊 41 · 訪問量 37萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章