zoukankan      html  css  js  c++  java
  • IList转化为DataSet,解决了System.nullable()的问题

    在做毕业设计时,需要用到这项功能,于是在网上搜索了一段代码,但是后来发现,在处理int类型时,会发生System.nullable的错误,于是自己查阅资料,进行了小小的改动,终于成功。。详细见一下方法。

      public static DataSet ConvertToDataSet<T>(IList<T> list)
            {
                if (list == null || list.Count <= 0)
                {
                    return null;
                }
    
                DataSet ds = new DataSet();
                DataTable dt = new DataTable(typeof(T).Name);
                DataColumn column;
                DataRow row;
    
                System.Reflection.PropertyInfo[] myPropertyInfo = typeof(T).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
    
                foreach (T t in list)
                {
                    if (t == null)
                    {
                        continue;
                    }
    
                    row = dt.NewRow();
    
                    for (int i = 0, j = myPropertyInfo.Length; i < j; i++)
                    {
                        System.Reflection.PropertyInfo pi = myPropertyInfo[i];
    
                        string name = pi.Name;
                       // if (pi.PropertyType == System.Nullable<>)
                       // {
                          //  pi.PropertyType = System.Int32;
                       // }
                        if (dt.Columns[name] == null)
                        {
                            if (pi.PropertyType.IsGenericType && pi.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))//这段是我进行修改和判断的地方
                            {
                                Type[] typeArray = pi.PropertyType.GetGenericArguments();
                                Type baseType = typeArray[0];
                                column = new DataColumn(name, baseType);
                            }
                            else
                            {
                                column = new DataColumn(name, pi.PropertyType);
                            }
                            dt.Columns.Add(column);
                        }
    
                        row[name] = pi.GetValue(t, null);
                    }
    
                    dt.Rows.Add(row);
                }
    
                ds.Tables.Add(dt);
    
                return ds;
            }
  • 相关阅读:
    scala -- 柯里化
    scala-- 高阶函数
    neo4j 数据库导入导出
    scala -- 模式匹配
    命名空间
    [BZOJ1018][SHOI2008]堵塞的交通traffic 线段树维护连通性
    [BZOJ1017][JSOI2008]魔兽地图DotR 树形dp
    [BZOJ1260][CQOI2007]涂色paint 区间dp
    [bzoj1787][Ahoi2008]Meet 紧急集合
    [BZOJ2243][SDOI2011]染色
  • 原文地址:https://www.cnblogs.com/chenyready/p/3044890.html
Copyright © 2011-2022 走看看