封装一个List集合和datatable相互转换的工具类



   /// <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);

原文地址:https://www.cnblogs.com/zzlblog/p/10013072.html

时间: 2024-08-28 07:08:53

封装一个List集合和datatable相互转换的工具类的相关文章

List集合和JSON互转工具类

public class JsonListUtil { /** * List<T> 转 json 保存到数据库 */ public static <T> String listToJson(List<T> ts) { String jsons = JSON.toJSONString(ts); return jsons; } /** * json 转 List<T> */ public static <T> List<T> jsonTo

xml字符串和java实体类相互转换JaxbXmlUtil工具类 附java实体类生成soap接口报文案例

JaxbXmlUtil工具类 package com.aiait.ivs.util; import java.io.StringReader; import java.io.StringWriter; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; /** * Jaxb工具类 xml和java类相互转换 * * @author sunj

结合AnyChart做报表:一个生成AnyChart图形XML数据的工具类

今天头有点痛,所以不能详细地写了,先把代码贴上来,等身体状况稍微好一点,再继续完善. 1.(主角)一个使用XML模板生成Anychart XML数据的工具类 /** * */ package com.common.anychart; import java.io.InputStream; import java.util.List; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.l

浅析Android Camera开发中的三个尺寸和三种变形 (贡献一个自适配Picturesize和Previewsize的工具类)

转至 (http://blog.csdn.net/yanzi1225627/article/details/17652643) 经常听人问Camera开发中,各种变形问题,今天有空就在此梳理总结下. 三个尺寸: 1.Surfaceview的尺寸 Surfaceview是用来预览Camera的,当它全屏时就是Screen的大小. 2.Picturesize的尺寸 这是拍照后的PictureSize尺寸. 3.Previewsize的尺寸 这是预览时帧数据的尺寸. 三种变形: 1.预览画面的物体长宽

一个加速产生 Spring JDBC RowMapper 的工具类

在使用Spring JdbcTemplate 时,编写 RowMapper 实在是一件累人的工作.于是我写了一个根据实体类产生 RowMapper 的工厂类 RowMapperFactory,来避免直接编写 RowMapper.RowMapperFactory 暂不支持枚举. 下面就是 RowMapperFactory: import org.springframework.jdbc.core.RowMapper; import java.lang.reflect.Method; import

[Unity]C#中 将XML和实体类之间进行相互转换的工具类

using System; using System.Xml; using System.Xml.Serialization; using System.IO; namespace LOTool { public class LO_XMLTool { #region 反序列化 /// <summary> /// 反序列化 /// </summary> /// <param name="type">类型</param> /// <pa

基于java反射的javabean和map相互转换的工具类

话不多说,代码如下 package com.study; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; /** * PackageName com.study * Description please write description. * User: yh * Time: 2016/11/29 16:57 */ public class mapUtil { /** * javaB

关于图片与base64相互转换的工具类

最近在编写平台对接软件,需要从Oracle中取出blob类型图片数据转换为base64字符串写入到xml中,这里记录一下用到的转换方法 // 将一张本地图片转化成Base64字符串 public static String GetImageStrFromPath(String imgPath) { InputStream in = null; byte[] data = null; // 读取图片字节数组 try { in = new FileInputStream(imgPath); data

C#.net开发 List与DataTable相互转换

在.NET开发中,操作关系型数据库提取数据经常用到DataTable.ASP.NET前后台数据绑定应用DataTable的时候似乎也很多,但是List集合比DataTable应用更加广泛,提取处理数据也更加方便,MVC绑定数据更倾向于List. 因此,我们会经常需要对List集合和DataTable数据进行互转,以下三个方法是实现List和DataTable互转,以及DataTable单行提取对象.好了,直接上代码了: 1.DataTable转List集合 /// <summary> ///