zoukankan      html  css  js  c++  java
  • C#DataTable转List<T>和List<T>转DataTable

    DataTable 转换为List 集合

    /// <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); });
                    prlist.ForEach(p =>
                    {
                        if (row[p.Name] != DBNull.Value)
                        {
                                p.SetValue(ob, row[p.Name], null);
                        }
                        else
                        {
                            if (p.PropertyType == typeof(string))
                            {
                                p.SetValue(ob, string.Empty, null);
                            }
                        }
    
                    });
                    //放入到返回的集合中.
                    oblist.Add(ob);
                }
                return oblist;
            }
    

      List<T>转DataTable

    public static class ListExtension
        {
            public static DataTable ListConvertDataTable<T>(List<T> model, string TableName) where T : class
            {
                try
                {
                    Type value = typeof(T);
                    List<PropertyInfo> list = new List<PropertyInfo>(value.GetProperties()); //属性列表
                    DataTable table = new DataTable();//实例化datatable
                    table.TableName = TableName; //表名
                    foreach (var property in list)
                    {
                        //获取属性数据类型
                        Type PropertyType = property.PropertyType;
                        //验证数据类型是否为空
                        if (PropertyType.IsGenericType && PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                        {
                            PropertyType = property.PropertyType.GetGenericArguments()[0];
                        }
                        table.Columns.Add(property.Name, PropertyType);
                    }
                    foreach (var dataValue in model)
                    {
                        DataRow row = table.NewRow();
                        list.ForEach(p => { row[p.Name] = p.GetValue(dataValue); });
                        table.Rows.Add(row);
                    }
                    return table;
                }
                catch (Exception ex)
                {
                    return null;
                }
            }
        }
    

      讲DataRow转成Model

            /// <summary>
            /// DataRow 转换成 Model
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="dr"></param>
            /// <returns></returns>
            public static T ConvertToModel<T>(this System.Data.DataRow dr) where T : new()
            {
                T model = new T();
                foreach (PropertyInfo pInfo in model.GetType().GetProperties())
                {
                    object val = getValueByColumnName(dr, pInfo.Name);
                    pInfo.SetValue(model, val, null);
                }
                return model;
            }
            /// <summary>
            /// 获取该列的值
            /// </summary>
            /// <param name="dr"></param>
            /// <param name="columnName"></param>
            /// <returns></returns>
            public static object getValueByColumnName(System.Data.DataRow dr, string columnName)
            {
                if (dr.Table.Columns.IndexOf(columnName) >= 0)
                {
                    if (dr[columnName] == DBNull.Value)
                    {
                        return null;
                    }
                    return dr[columnName];
                }
                return null;
            }
    

      

  • 相关阅读:
    多层装饰器执行顺序
    flask之 中间件 蓝图 falsk请求上下文 rquirements.txt threading.local 偏函数
    flask 之 在flask中使用websocket
    flask 之项目分文件使用sqlalchemy+flask-migrate djagno多数据库
    flask之六 sqlachemy详解 scoped_session线程安全 基本增删改查 多对多关系建立和操作 flask-sqlalchemy的使用
    远程连接linux开发项目
    INT104-lab9
    INT104-lab8
    INT104-lab7
    Java-数据结构-泛型BST-CPT102-tutorial Week6
  • 原文地址:https://www.cnblogs.com/sunliyuan/p/12464078.html
Copyright © 2011-2022 走看看