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

2020-12-13 05:19

阅读:214

标签:style   c   class   blog   code   java   

soscw.com,搜素材soscw.com,搜素材
    /// 
    /// 扩展方法类
   /// 
    public static class CommonExtension
    {
        /// 
        /// 数据类型对应转换方法字典
      /// 
        static Dictionaryobject, object>> dic_convert = new Dictionaryobject, object>>();

        /// 
        /// 构造函数
      /// 
        static CommonExtension()
        {
            Funcobject, 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);
        }
        /// 
        /// 获取DataTable的列名集合
        /// 
        public static IListstring> GetColumnNames(this DataTable dt)
        {
            if (dt == null || dt.Rows.Count == 0)
            {
                return new Liststring>(0);
            }
            //由于集合中的元素是确定的,所以可以指定元素的个数,系统就不会分配多余的空间,效率会高点
            IListstring> list = new Liststring>(dt.Columns.Count);
            foreach (DataColumn dc in dt.Columns)
            {
                list.Add(dc.ColumnName);
            }

            return list;
        }

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

            Liststring, object>> list = new Liststring, object>>();

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

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

        /// 
        /// 把DataTable转换成泛型列表
        /// 
        /// 类型
        /// 
        /// 
        public static List ToList(this DataTable dt) where T : new()
        {
            var list = new List();
            if (dt == null || dt.Rows.Count == 0)
            {
                return list;
            }
            // 获得此模型的公共属性
            var plist = new List(typeof(T).GetProperties());
            // 循环行
            foreach (DataRow row in dt.Rows)
            {
                var t = new T();
                // 循环列
                foreach (DataColumn dc in dt.Columns)
                {
                    var value = 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;
        }

        /// 
        /// 将DataTable实例转换成List
        /// 
        /// Model类型列表
        /// DataTable对象
        /// 
        public static List ToListSmart(this DataTable dt) where T : new()
        {
            // 定义集合
            List list = new List();
            if (dt == null || dt.Rows.Count == 0)
            {
                return list;
            }
            // 获得此模型的类型
            Type type = typeof(T);
            // 获得此模型的公共属性
            var plist = new List(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();
                    // 循环属性列表
                    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

 

DataTable扩展方法ToList()、ToJSON()、ToArrayList(),搜素材,soscw.com

DataTable扩展方法ToList()、ToJSON()、ToArrayList()

标签:style   c   class   blog   code   java   

原文地址:http://www.cnblogs.com/beijia/p/DataTableExtension.html


评论


亲,登录后才可以留言!