惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

酷 壳 – CoolShell
酷 壳 – CoolShell
H
Hacker News: Front Page
P
Palo Alto Networks Blog
T
ThreatConnect
Apple Machine Learning Research
Apple Machine Learning Research
博客园_首页
T
True Tiger Recordings
P
Privacy & Cybersecurity Law Blog
B
Blog
IT之家
IT之家
Last Week in AI
Last Week in AI
F
Full Disclosure
Hacker News: Ask HN
Hacker News: Ask HN
C
Comments on: Blog
Microsoft Azure Blog
Microsoft Azure Blog
C
Cybersecurity and Infrastructure Security Agency CISA
Microsoft Security Blog
Microsoft Security Blog
博客园 - 【当耐特】
N
News and Events Feed by Topic
NISL@THU
NISL@THU
腾讯CDC
雷峰网
雷峰网
Security Latest
Security Latest
李成银的技术随笔
M
Microsoft Research Blog - Microsoft Research
L
LangChain Blog
L
Lohrmann on Cybersecurity
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
C
Check Point Blog
Y
Y Combinator Blog
Recent Announcements
Recent Announcements
博客园 - Franky
N
News | PayPal Newsroom
V
V2EX
A
About on SuperTechFans
The Register - Security
The Register - Security
月光博客
月光博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google Online Security Blog
Google Online Security Blog
MyScale Blog
MyScale Blog
Cisco Talos Blog
Cisco Talos Blog
Vercel News
Vercel News
WordPress大学
WordPress大学
C
Cyber Attacks, Cyber Crime and Cyber Security
The Hacker News
The Hacker News
IntelliJ IDEA : IntelliJ IDEA – the Leading IDE for Professional Development in Java and Kotlin | The JetBrains Blog
IntelliJ IDEA : IntelliJ IDEA – the Leading IDE for Professional Development in Java and Kotlin | The JetBrains Blog
爱范儿
爱范儿
A
Arctic Wolf
L
LINUX DO - 最新话题
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More

博客园 - 咕咕传说

屠夫兄的思路龙头思维 走刀口交割单 批量杀死锁 咕咕 111 Nginx配置多个server RestSharp的简单用法 关于运行在Docker的程序,无法远程访问数据库的解决方案! 重要的开源项目 SQL 某月每天的数据 或者某天每小时的数据 或者 某段时间每个月月数据,和该月每天的数据 Asp.net获取客户端的IP地址排除::1 EF 筛选列包含NULL会报错 博文阅读密码验证 - 博客园 layUI关于table编辑列支持方向键功能 .NET CORE 发布IIS问题收集 VS2019最新源代码管理工具+附下载地址 关于Mysql可视化工具Navicat Premium12激活使用【亲测】 经典SQL 语句 博文阅读密码验证 - 博客园 事务的四种隔离级别 [转载]
缓存类2
咕咕传说 · 2020-12-01 · via 博客园 - 咕咕传说
 public static class ConvertData
    { 
        #region 范型集合和DataSet之间的转换

        /// <summary>
        /// 数据集合转换成DataSet
        /// </summary>
        /// <param name="datas">数据集合转换成的Object数组</param>
        /// <returns></returns>
        public static DataSet ToDataSet(object[] datas)
        {
            DataSet result = new DataSet();
            DataTable _DataTable = new DataTable();
            if (datas.Length > 0)
            {
                PropertyInfo[] propertys = datas[0].GetType().GetProperties();
                foreach (PropertyInfo pi in propertys)
                {
                    if (pi.PropertyType.ToString().IndexOf("EntitySet") >= 0 || pi.PropertyType.ToString().IndexOf("EntityRef") >= 0)
                    {
                        continue;
                    }
                    _DataTable.Columns.Add(pi.Name, GetNotNullableType(pi.PropertyType));
                }

                for (int i = 0; i < datas.Length; i++)
                {
                    ArrayList tempList = new ArrayList();
                    foreach (PropertyInfo pi in propertys)
                    {
                        if (pi.PropertyType.ToString().IndexOf("EntitySet") >= 0 || pi.PropertyType.ToString().IndexOf("EntityRef") >= 0)
                        {
                            continue;
                        }
                        object obj = pi.GetValue(datas[i], null);
                        tempList.Add(obj);
                    }
                    object[] array = tempList.ToArray();
                    _DataTable.LoadDataRow(array, true);
                }
            }
            result.Tables.Add(_DataTable);
            return result;
        }

        /// <summary>
        /// 数据集合转化成DataTable
        /// Landry add at: 2010-12-08
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        public static DataTable ToDataTable(object[] datas)
        {
            return ToDataTable(datas, true);
        }

        public static DataTable ToDataTable(object[] datas, bool isNeedColumnType = true)
        {
            if (datas == null) { return null; }
            DataTable _DataTable = new DataTable();
            if (datas.Length > 0)
            {
                PropertyInfo[] propertys = datas[0].GetType().GetProperties();
                foreach (PropertyInfo pi in propertys)
                {
                    if (isNeedColumnType)
                    {
                        _DataTable.Columns.Add(pi.Name, GetNotNullableType(pi.PropertyType));
                    }
                    else
                    {
                        _DataTable.Columns.Add(pi.Name);
                    }
                }

                foreach (object obj in datas)
                {
                    DataRow newRow = _DataTable.NewRow();
                    foreach (PropertyInfo field in propertys)
                    {
                        newRow[field.Name] = field.GetValue(obj, null);
                    }
                    _DataTable.Rows.Add(newRow);
                }
            }
            _DataTable.TableName = "Table1";//罗鹏加的,防止WCF返回报错  BY 2012-11-07
            return _DataTable;
        }

        /// <summary>
        /// 范型集合转换成DataTable
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="datas"></param>
        /// <returns></returns>
        public static DataTable ToDataTable<T>(IList<T> datas) where T : class, new()
        {
            if (datas == null) { return null; }
            DataTable _DataTable = new DataTable();
            var pis = typeof(T).GetProperties();
            foreach (var pi in pis)
            {
                //if (pi.GetCustomAttributes(false).Any(t => t is DataMemberAttribute))
                //{
                _DataTable.Columns.Add(pi.Name, GetNotNullableType(pi.PropertyType));
                //}
            }
            foreach (var data in datas)
            {
                ArrayList tempList = new ArrayList();
                foreach (var pi in pis)
                {
                    //if (pi.GetCustomAttributes(false).Any(t => t is DataMemberAttribute))
                    //{
                    tempList.Add(pi.GetValue(data, null));
                    //}
                }
                _DataTable.LoadDataRow(tempList.ToArray(), true);
            }
            _DataTable.TableName = "Table1";//罗鹏加的,防止WCF返回报错  BY 2012-11-07
            return _DataTable;
        } 

        public static List<T> ConvertToEx<T>(DataTable dt) where T : new()
        {
            if (dt == null) return null;
            if (dt.Rows.Count <= 0) return null;

            List<T> list = new List<T>();
            Type type = typeof(T);
            PropertyInfo[] propertyInfos = type.GetProperties();  //获取泛型的属性
            List<DataColumn> listColumns = dt.Columns.Cast<DataColumn>().ToList();  //获取数据集的表头,以便于匹配
            T t;
            foreach (DataRow dr in dt.Rows)
            {
                t = new T();
                foreach (PropertyInfo propertyInfo in propertyInfos)
                {
                    try
                    {
                        DataColumn dColumn = listColumns.Find(name => name.ToString().ToUpper() == propertyInfo.Name.ToUpper());  //查看是否存在对应的列名
                        if (dColumn != null)
                            propertyInfo.SetValue(t, dr[propertyInfo.Name], null);  //赋值
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(ex.Message);
                    }
                }
                list.Add(t);
            }
            return list;
        }

        /// <summary>
        /// 数据集合转化成泛型 List
        /// Landry add at: 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="datas"></param>
        /// <returns></returns>
        public static List<T> ObjectToIList<T>(object[] datas) where T : class
        {
            if (datas == null) { return null; }
            Type targetType = typeof(T);
            PropertyInfo[] targetPropertyInfos = targetType.GetProperties();
            FieldInfo[] objFieldInfos = datas[0].GetType().GetFields();
            List<T> resultList = new List<T>();
            foreach (object obj in datas)
            {
                T targetObj = (T)Activator.CreateInstance(typeof(T));
                foreach (FieldInfo field in objFieldInfos)
                {
                    PropertyInfo pi = targetPropertyInfos.SingleOrDefault(p => p.Name == field.Name);
                    if (pi != null)
                    {
                        pi.SetValue(targetObj, field.GetValue(obj), null);
                    }
                }
                resultList.Add(targetObj);
            }
            return resultList;
        }

        /// <summary>
        /// 泛型集合转换DataSet
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list">泛型集合</param>
        /// <returns></returns>
        public static DataSet IListToDataSet<T>(IList<T> list) where T : class
        {
            return IListToDataSet<T>(list, null);
        }


        /// <summary>
        /// 泛型集合转换DataSet
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="p_List">泛型集合</param>
        /// <param name="p_PropertyName">待转换属性名数组</param>
        /// <returns></returns>
        public static DataSet IListToDataSet<T>(IList<T> p_List, params string[] p_PropertyName) where T : class
        {
            List<string> propertyNameList = new List<string>();
            if (p_PropertyName != null)
                propertyNameList.AddRange(p_PropertyName);

            DataSet result = new DataSet();
            DataTable _DataTable = new DataTable();
            if (p_List.Count > 0)
            {
                PropertyInfo[] propertys = p_List[0].GetType().GetProperties();
                foreach (PropertyInfo pi in propertys)
                {
                    if (pi.PropertyType.ToString().IndexOf("EntitySet") >= 0 || pi.PropertyType.ToString().IndexOf("EntityRef") >= 0)
                    {
                        continue;
                    }
                    if (propertyNameList.Count == 0)
                    {
                        // 没有指定属性的情况下全部属性都要转换
                        _DataTable.Columns.Add(pi.Name, GetNotNullableType(pi.PropertyType));
                    }
                    else
                    {
                        if (propertyNameList.Contains(pi.Name))
                            _DataTable.Columns.Add(pi.Name, GetNotNullableType(pi.PropertyType));
                    }
                }

                for (int i = 0; i < p_List.Count; i++)
                {
                    ArrayList tempList = new ArrayList();
                    foreach (PropertyInfo pi in propertys)
                    {
                        if (pi.PropertyType.ToString().IndexOf("EntitySet") >= 0 || pi.PropertyType.ToString().IndexOf("EntityRef") >= 0)
                        {
                            continue;
                        }
                        if (propertyNameList.Count == 0)
                        {
                            object obj = pi.GetValue(p_List[i], null);
                            tempList.Add(obj);
                        }
                        else
                        {
                            if (propertyNameList.Contains(pi.Name))
                            {
                                object obj = pi.GetValue(p_List[i], null);
                                tempList.Add(obj);
                            }
                        }
                    }
                    object[] array = tempList.ToArray();
                    _DataTable.LoadDataRow(array, true);
                }
            }
            result.Tables.Add(_DataTable);
            return result;
        }

        /// <summary>
        /// DataSet装换为泛型集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="p_DataSet">DataSet</param>
        /// <param name="p_TableIndex">待转换数据表索引</param>
        /// <returns></returns>
        public static IList<T> DataSetToIList<T>(DataSet p_DataSet, int p_TableIndex) where T : class
        {
            if (p_DataSet == null || p_DataSet.Tables.Count < 0)
                return null;
            if (p_TableIndex > p_DataSet.Tables.Count - 1)
                return null;
            if (p_TableIndex < 0)
                p_TableIndex = 0;

            DataTable p_Data = p_DataSet.Tables[p_TableIndex];
            // 返回值初始化
            IList<T> result = new List<T>();
            for (int j = 0; j < p_Data.Rows.Count; j++)
            {
                T _t = (T)Activator.CreateInstance(typeof(T));
                PropertyInfo[] propertys = _t.GetType().GetProperties();
                foreach (PropertyInfo pi in propertys)
                {
                    for (int i = 0; i < p_Data.Columns.Count; i++)
                    {
                        // 属性与字段名称一致的进行赋值
                        if (pi.Name.Equals(p_Data.Columns[i].ColumnName))
                        {
                            // 数据库NULL值单独处理
                            if (p_Data.Rows[j][i] != DBNull.Value)
                                pi.SetValue(_t, p_Data.Rows[j][i], null);
                            else
                                pi.SetValue(_t, null, null);
                            break;
                        }
                    }
                }
                result.Add(_t);
            }
            return result;
        }

        /// <summary>
        /// DataSet装换为泛型集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="p_DataSet">DataSet</param>
        /// <param name="p_TableName">待转换数据表名称</param>
        /// <returns></returns>
        public static IList<T> DataSetToIList<T>(DataSet p_DataSet, string p_TableName) where T : class
        {
            int _TableIndex = 0;
            if (p_DataSet == null || p_DataSet.Tables.Count < 0)
                return null;
            if (string.IsNullOrEmpty(p_TableName))
                return null;
            for (int i = 0; i < p_DataSet.Tables.Count; i++)
            {
                // 获取Table名称在Tables集合中的索引值
                if (p_DataSet.Tables[i].TableName.Equals(p_TableName))
                {
                    _TableIndex = i;
                    break;
                }
            }
            return DataSetToIList<T>(p_DataSet, _TableIndex);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="p_type"></param>
        /// <returns></returns>
        public static Type GetNotNullableType(Type p_type)
        {
            if (p_type == typeof(Int16?))
            {
                return typeof(Int16);
            }
            if (p_type == typeof(Int32?))
            {
                return typeof(Int32);
            }
            if (p_type == typeof(Int64?))
            {
                return typeof(Int64);
            }
            if (p_type == typeof(decimal?))
            {
                return typeof(decimal);
            }
            if (p_type == typeof(double?))
            {
                return typeof(double);
            }
            if (p_type == typeof(DateTime?))
            {
                return typeof(DateTime);
            }
            if (p_type == typeof(Boolean?))
            {
                return typeof(Boolean);
            }
            if (p_type == typeof(Guid?))
            {
                return typeof(Guid);
            }
            if (p_type == typeof(byte?))
            {
                return typeof(byte);
            }
            if (p_type == typeof(float?))
            {
                return typeof(float);
            }
            return p_type;
        }
        #endregion
    }