美文网首页
枚举转换dataTable

枚举转换dataTable

作者: hanscang | 来源:发表于2020-03-30 18:26 被阅读0次
        /// <summary>
        /// 枚举转换dataTable
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        public DataTable GetTableFromEnum<T>(IEnumerable<T> collection)
        {
            var props = typeof(T).GetProperties();
            var dt = new DataTable();
            //创建
            dt.Columns.AddRange
                (
                //可空类型转换为值类型,内部处理异常及内部对象 
                    props.Select
                        (
                            p => new DataColumn(p.Name, ToStruct(p.PropertyType))
                        ).ToArray()
                  );

            if (collection.Count() > 0)
            {
                for (int i = 0; i < collection.Count(); i++)
                {
                    ArrayList tempList = new ArrayList();
                    //遍历枚举
                    foreach (PropertyInfo pi in props)
                    {
                        //遍历枚举内部值
                        object obj = pi.GetValue(collection.ElementAt(i), null);
                        tempList.Add(obj);
                    }
                    object[] array = tempList.ToArray();
                    //赋值给表
                    dt.LoadDataRow(array, true);
                }
            }
            return dt;
        }

值类型转换方法:ToStruct

相关文章

网友评论

      本文标题:枚举转换dataTable

      本文链接:https://www.haomeiwen.com/subject/amtbuhtx.html