1. 程式人生 > >封裝一個List集合和datatable相互轉換的工具類

封裝一個List集合和datatable相互轉換的工具類

oda info data 反射 arr key 建表 contain 信息



   /// <summary>
    /// List轉換為DataTable對象
    /// </summary>
   public class ListTranTableModel
    {
        /// <summary>
        /// 新增的列名稱
        /// </summary>
        public string addColumName { get; set; }
        /// <summary>
        /// 新增列的默認信息
        /// </summary>
        public
TableCloumDInfo tableCloumDInfo { get; set; } }


  /// <summary>
    /// 列的默認信息
    /// </summary>
  public  class TableCloumDInfo
    {
        //列的數據類型
        public Type dataType { get; set; }
        //列的默認值
        public object defaultValue { get; set; }
    }
  /// <summary>
    /// 批量導入信息基類
    
/// </summary> public class DatableBulk_ImportBase { /// <summary> /// 重命名的列集合 /// </summary> public Dictionary<string, string> PropertyRenameDic { get; set; } /// <summary> /// 要指定輸出的列名稱 /// </summary> public string
[] PropertyName { get; set; } /// <summary> /// 數據類型 /// </summary> public string Category { get; set; } /// <summary> /// 批量導入信息時的說明信息 /// </summary> public string ErrorInfo { get; set; } }
    /// <summary>
    /// 批量導入信息數據Table屬性操作對象
    /// </summary>
    public class DatableProperty : DatableBulk_ImportBase
    {
    }

public static class ListTranDataTableHelper
    {
        /// <summary>    
        /// 將集合類轉換成DataTable    
        /// </summary>    
        /// <param name="list">集合</param>    
        /// <returns></returns>    
        private static DataTable ToDataTableTow(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);
                }
                foreach (object t in list)
                {
                    ArrayList tempList = new ArrayList();
                    foreach (PropertyInfo pi in propertys)
                    {
                        object obj = pi.GetValue(t, null);
                        tempList.Add(obj);
                    }
                    object[] array = tempList.ToArray();
                    result.LoadDataRow(array, true);
                }
            }
            return result;
        }

        /// <summary>    
        /// DataTable 轉換為List 集合    
        /// </summary>    
        /// <typeparam name="TResult">類型</typeparam>    
        /// <param name="dt">DataTable</param>    
        /// <returns></returns>    
        public static List<T> ToList<T>(this DataTable dt) where T : class, new()
        {
            //創建一個屬性的列表    
            List<PropertyInfo> prlist = new List<PropertyInfo>();
            //獲取TResult的類型實例  反射的入口    
            Type t = typeof(T);

            //獲得TResult 的所有的Public 屬性 並找出TResult屬性和DataTable的列名稱相同的屬性(PropertyInfo) 並加入到屬性列表     
            Array.ForEach<PropertyInfo>(t.GetProperties(), p => { if (dt.Columns.IndexOf(p.Name) != -1) prlist.Add(p); });

            //創建返回的集合    
            List<T> oblist = new List<T>();

            foreach (DataRow row in dt.Rows)
            {
                //創建TResult的實例    
                T ob = new T();
                //找到對應的數據  並賦值    
                prlist.ForEach(p => { if (row[p.Name] != DBNull.Value) p.SetValue(ob, row[p.Name], null); });
                //放入到返回的集合中.    
                oblist.Add(ob);
            }
            return oblist;
        }

        /// <summary>     
        /// 轉化一個DataTable    
        /// </summary>      
        /// <typeparam name="T"></typeparam>    
        /// <param name="list"></param>    
        /// <returns></returns>    
        public static DataTable ToDataTable<T>(this IEnumerable<T> list)
        {
            //創建屬性的集合    
            List<PropertyInfo> pList = new List<PropertyInfo>();
            //獲得反射的入口    
            Type type = typeof(T);
            DataTable dt = new DataTable();
            //把所有的public屬性加入到集合 並添加DataTable的列    
            Array.ForEach<PropertyInfo>(type.GetProperties(), p => { pList.Add(p); dt.Columns.Add(p.Name, p.PropertyType); });
            foreach (var item in list)
            {
                //創建一個DataRow實例    
                DataRow row = dt.NewRow();
                //給row 賦值    
                pList.ForEach(p => row[p.Name] = p.GetValue(item, null));
                //加入到DataTable    
                dt.Rows.Add(row);
            }
            return dt;
        }

        /// <summary>    
        /// 將泛型集合類轉換成DataTable    

        /// </summary>    
        /// <typeparam name="T">集合項類型</typeparam>    

        /// <param name="list">集合</param>    
        /// <returns>數據集(表)</returns>    
        public static DataTable ToDataTable<T>(IList<T> list)
        {
            return ToDataTable<T>(list,new Dictionary<string, string>(), null);

        }

        /**/

        /// <summary>    
        /// 將泛型集合類轉換成DataTable    
        /// </summary>    
        /// <typeparam name="T">集合項類型</typeparam>    
        /// <param name="list">集合</param>    
        /// <param name="="propertyRenameDic">需要指定重命名的列集合</param>
        /// <param name="propertyName">需要返回的列的列名</param>    
        /// <returns>數據集(表)</returns>    
        public static DataTable ToDataTable<T>(IList<T> list, Dictionary<string, string> propertyRenameDic, params string[] propertyName)
        {
            List<string> propertyNameList = new List<string>();
            if (propertyName != null)
            {
                propertyNameList.AddRange(propertyName);
                if (propertyRenameDic.Count>0)
                {
                    foreach (var item in propertyRenameDic)
                    {
                        propertyNameList.Remove(item.Key);
                        propertyNameList.Add(item.Value);
                    }  
                }
            }
            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);
                        if (propertyRenameDic.Keys.Contains(pi.Name))
                        {
                            if (propertyNameList.Contains(propertyRenameDic[pi.Name]))
                                result.Columns.Add(propertyRenameDic[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 (propertyRenameDic.Keys.Contains(pi.Name))
                            {
                                if (propertyNameList.Contains(pi.Name) || propertyNameList.Contains(propertyRenameDic[pi.Name]))
                                {
                                    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;
        }

        /// <summary>
        /// 將DataTable新增幾列並指定默認值
        /// </summary>
        /// <param name="vTable">源表</param>
        /// <param name="list">增加的列集合</param>
        /// <returns></returns>
        public static DataTable AddColums(DataTable vTable, List<ListTranTableModel> list)
        {
            foreach (var item in list)
            {
                //添加一新列,其值為默認值
                 DataColumn dc = new DataColumn(item.addColumName, item.tableCloumDInfo.dataType);
                dc.DefaultValue = item.tableCloumDInfo.defaultValue;
                dc.AllowDBNull = false;//這在創建表的時候,起作用,在為已有表新增列的時候,不起作用
                vTable.Columns.Add(dc);
            }
            return vTable;
        }
    }

調用舉例

 DataTable dt = ListTranDataTableHelper.ToDataTable(listv, DatableProperty.PropertyRenameDic);

封裝一個List集合和datatable相互轉換的工具類