C# DataTable、DataSet、List、相互轉換

 

 DataTable轉LIst

/// <summary> 
    /// 利用反射將DataTable轉換爲List<T>對象
    /// </summary> 
    /// <param name="dt">DataTable 對象</param> 
    /// <returns>List<T>集合</returns> 
    public static List<T> DataTableToList<T>(DataTable dt) where T :class,new ()
    { 
      // 定義集合 
      List<T> ts = new List<T>(); 
      //定義一個臨時變量 
      string tempName = string.Empty; 
      //遍歷DataTable中全部的數據行 
      foreach (DataRow dr in dt.Rows) 
      { 
        T t = new T(); 
        // 得到此模型的公共屬性 
        PropertyInfo[] propertys = t.GetType().GetProperties(); 
        //遍歷該對象的全部屬性 
        foreach (PropertyInfo pi in propertys) 
        { 
          tempName = pi.Name;//將屬性名稱賦值給臨時變量 
          //檢查DataTable是否包含此列(列名==對象的屬性名)  
          if (dt.Columns.Contains(tempName)) 
          { 
            //取值 
            object value = dr[tempName];
             //若是非空,則賦給對象的屬性 
             if (value != DBNull.Value)
             {
               pi.SetValue(t,value,null); 
             }  
          } 
        } 
        //對象添加到泛型集合中 
        ts.Add(t); 
      } 
      return ts; 
    }

 

List轉DataSet

 /// <summary> 
        /// List轉換成DataSet 
        /// </summary> 
        /// <typeparam name="T">類型</typeparam> 
        /// <param name="list">將要轉換的List</param> 
        /// <returns></returns> 
        public DataSet ConvertToDataSet<T>(IList<T> list)
        {
            if (list == null || list.Count <= 0)
            {
                return null;
            }
            DataSet ds = new DataSet();
            DataTable dt = new DataTable(typeof(T).Name);
            DataColumn column;
            DataRow row;
            System.Reflection.PropertyInfo[] myPropertyInfo = typeof(T).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
            foreach (T t in list)
            {
                if (t == null)
                {
                    continue;
                }
                row = dt.NewRow();
                for (int i = 0, j = myPropertyInfo.Length; i < j; i++)
                {
                    System.Reflection.PropertyInfo pi = myPropertyInfo[i];
                    string name = pi.Name;
                    if (dt.Columns[name] == null)
                    {
                        column = new DataColumn(name, pi.PropertyType);
                        dt.Columns.Add(column);
                    }
                    row[name] = pi.GetValue(t, null);
                }
                dt.Rows.Add(row);
            }
            ds.Tables.Add(dt);
            return ds;
        }

 

List轉DataSet

private DataTable ToDataTable<T>(List<T> items)
        {
            var tb = new DataTable(typeof(T).Name);
            PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (PropertyInfo prop in props)
            {
                Type t = GetCoreType(prop.PropertyType);
                tb.Columns.Add(prop.Name, t);
            }
            foreach (T item in items)
            {
                var values = new object[props.Length];
                for (int i = 0; i < props.Length; i++)
                {
                    values[i] = props[i].GetValue(item, null);
                }
                tb.Rows.Add(values);
            }
            return tb;
        }
        public static bool IsNullable(Type t)
        {
            return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
        }

        public static Type GetCoreType(Type t)
        {
            if (t != null && IsNullable(t))
            {
                if (!t.IsValueType)
                {
                    return t;
                }
                else
                {
                    return Nullable.GetUnderlyingType(t);
                }
            }
            else
            {
                return t;
            }
        }
相關文章
相關標籤/搜索