首页 > 代码库 > DataTable扩展方法ToList<T>()、ToJSON()、ToArrayList()

DataTable扩展方法ToList<T>()、ToJSON()、ToArrayList()

    /// <summary>
    /// 扩展方法类
   /// </summary>
    public static class CommonExtension
    {
        /// <summary>
        /// 数据类型对应转换方法字典
      /// </summary>
        static Dictionary<Type, Func<object, object>> dic_convert = new Dictionary<Type, Func<object, object>>();

        /// <summary>
        /// 构造函数
      /// </summary>
        static CommonExtension()
        {
            Func<object, object> f = null;
            //string
            f = (val) => Convert.ToString(val);
            dic_convert.Add(typeof(string), f);
            //int
            f = (val) => Convert.ToInt32(val);
            dic_convert.Add(typeof(int), f);
            //long
            f = (val) => Convert.ToInt64(val);
            dic_convert.Add(typeof(long), f);
            //double
            f = (val) => Convert.ToDouble(val);
            dic_convert.Add(typeof(double), f);
            //float
            f = (val) => (float)(val);
            dic_convert.Add(typeof(float), f);
            //decimal
            f = (val) => Convert.ToDecimal(val);
            dic_convert.Add(typeof(decimal), f);
            //datetime
            f = (val) => Convert.ToDateTime(val);
            dic_convert.Add(typeof(DateTime), f);
            //bool
            f = (val) => Convert.ToBoolean(val);
            dic_convert.Add(typeof(bool), f);
            //byte
            f = (val) => Convert.ToByte(val);
            dic_convert.Add(typeof(byte), f);
            //char
            f = (val) => Convert.ToChar(val);
            dic_convert.Add(typeof(char), f);
            //null
            f = (val) => (null);
            dic_convert.Add(typeof(DBNull), f);
        }
        /// <summary>
        /// 获取DataTable的列名集合
        /// </summary>
        public static IList<string> GetColumnNames(this DataTable dt)
        {
            if (dt == null || dt.Rows.Count == 0)
            {
                return new List<string>(0);
            }
            //由于集合中的元素是确定的,所以可以指定元素的个数,系统就不会分配多余的空间,效率会高点
            IList<string> list = new List<string>(dt.Columns.Count);
            foreach (DataColumn dc in dt.Columns)
            {
                list.Add(dc.ColumnName);
            }

            return list;
        }

        /// <summary>
        /// 将 DataTable 序列化成 json 字符串
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string ToJson(this DataTable dt)
        {
            if (dt == null || dt.Rows.Count == 0)
            {
                return "[]";
            }
            JavaScriptSerializer myJson = new JavaScriptSerializer();

            List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();

            foreach (DataRow dr in dt.Rows)
            {
                Dictionary<string, object> result = new Dictionary<string, object>();
                foreach (DataColumn dc in dt.Columns)
                {
                    result.Add(dc.ColumnName, dr[dc].ToString());
                }
                list.Add(result);
            }
            return myJson.Serialize(list);
        }

        /// <summary>
        /// 将 DataTable 序列化成 ArrayList
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static ArrayList ToArrayList(this DataTable dt)
        {
            ArrayList arrayList = new ArrayList();
            if (dt != null)
            {
                foreach (DataRow dataRow in dt.Rows)
                {
                    Dictionary<string, object> dictionary = new Dictionary<string, object>();  //实例化一个参数集合  
                    foreach (DataColumn dataColumn in dt.Columns)
                    {
                        dictionary.Add(dataColumn.ColumnName, dataRow[dataColumn.ColumnName].ToString());
                    }
                    arrayList.Add(dictionary); 
                }
            }
            return arrayList;
        }

        /// <summary>
        /// 把DataTable转换成泛型列表
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static List<T> ToList<T>(this DataTable dt) where T : new()
        {
            var list = new List<T>();
            if (dt == null || dt.Rows.Count == 0)
            {
                return list;
            }
            // 获得此模型的公共属性
            var plist = new List<PropertyInfo>(typeof(T).GetProperties());
            // 循环行
            foreach (DataRow row in dt.Rows)
            {
                var t = new T();
                // 循环列
                foreach (DataColumn dc in dt.Columns)
                {
                    var value =http://www.mamicode.com/ row[dc.ColumnName];
                    // 判断值是否有效
                    if (Convert.IsDBNull(value))
                        continue;

                    //var p = info.GetType().GetProperty(dc.ColumnName);
                    var p = plist.FirstOrDefault(c => c.Name.Equals(dc.ColumnName, StringComparison.CurrentCultureIgnoreCase));
                    // 判断此属性是否有Setter
                    if (p == null || !p.CanWrite)
                        continue;

                    if (dic_convert.ContainsKey(p.PropertyType))
                    {
                        var val = dic_convert[p.PropertyType].Invoke(value);
                        p.SetValue(t, val, null);
                    }
                }
                list.Add(t);
            }
            dt.Dispose();
            dt = null;

            return list;
        }

        /// <summary>
        /// 将DataTable实例转换成List<T>
        /// </summary>
        /// <typeparam name="T">Model类型</typeparam>列表
        /// <param name="dt">DataTable对象</param>
        /// <returns></returns>
        public static List<T> ToListSmart<T>(this DataTable dt) where T : new()
        {
            // 定义集合
            List<T> list = new List<T>();
            if (dt == null || dt.Rows.Count == 0)
            {
                return list;
            }
            // 获得此模型的类型
            Type type = typeof(T);
            // 获得此模型的公共属性
            var plist = new List<PropertyInfo>(type.GetProperties());
            // 获取列的个数
            int col_cnt = dt.Columns.Count;
            T t;
            if (plist.Count >= col_cnt)
            {
                #region 循环列给属性赋值方式
                foreach (DataRow row in dt.Rows)
                {
                    t = new T();
                    // 循环列
                    foreach (DataColumn dc in dt.Columns)
                    {
                        // 根据列名查找属性
                        PropertyInfo pi = plist.Find(p => p.Name.Equals(dc.ColumnName, StringComparison.CurrentCultureIgnoreCase));
                        if (pi != null)
                        {
                            // 判断此属性是否有Setter
                            if (!pi.CanWrite)
                                continue;
                            // 判断值是否有效
                            if (Convert.IsDBNull(row[pi.Name]))
                                continue;

                            if (dic_convert.ContainsKey(pi.PropertyType))
                            {
                                var val = dic_convert[pi.PropertyType].Invoke(row[pi.Name]);
                                pi.SetValue(t, val, null);
                            }
                        }
                    }
                    list.Add(t);
                }
                #endregion
            }
            else
            {
                #region 循环属性查找列对应的值
                foreach (DataRow row in dt.Rows)
                {
                    t = System.Activator.CreateInstance<T>();
                    // 循环属性列表
                    foreach (PropertyInfo pi in plist)
                    {
                        // 检查DataTable是否包含此列
                        if (dt.Columns.Contains(pi.Name))
                        {
                            // 判断此属性是否有Setter
                            if (!pi.CanWrite)
                                continue;
                            // 判断值是否有效
                            if (row[pi.Name] == DBNull.Value)
                                continue;

                            if (dic_convert.ContainsKey(pi.PropertyType))
                            {
                                var val = dic_convert[pi.PropertyType].Invoke(row[pi.Name]);
                                pi.SetValue(t, val, null);
                            }
                        }
                    }
                    list.Add(t);
                }
                #endregion
            }

            return list;
        }

        #endregion
    }
View Code