zoukankan      html  css  js  c++  java
  • 将一个列表转换成DataTable,如果列表为空将返回空的DataTable结构

         /// <summary>
            /// 将一个列表转换成DataTable,如果列表为空将返回空的DataTable结构
            /// </summary>
            /// <typeparam name="T">要转换的数据类型</typeparam>
            /// <param name="entityList">实体对象列表</param>
            public static DataTable EntityListToDataTable<T>(List<T> entityList)
            {
                DataTable dt = new DataTable();

                //取类型T所有Propertie
                Type entityType = typeof(T);
                PropertyInfo[] entityProperties = entityType.GetProperties();
                Type colType = null;
                foreach (PropertyInfo propInfo in entityProperties)
                {

                    if (propInfo.PropertyType.IsGenericType)
                    {
                        colType = Nullable.GetUnderlyingType(propInfo.PropertyType);
                    }
                    else
                    {
                        colType = propInfo.PropertyType;
                    }

                    if (colType.FullName.StartsWith("System"))
                    {
                        dt.Columns.Add(propInfo.Name, colType);
                    }
                }

                if (entityList != null && entityList.Count > 0)
                {
                    foreach (T entity in entityList)
                    {
                        DataRow newRow = dt.NewRow();
                        foreach (PropertyInfo propInfo in entityProperties)
                        {
                            if (dt.Columns.Contains(propInfo.Name))
                            {
                                object objValue = propInfo.GetValue(entity, null);
                                newRow[propInfo.Name] = objValue == null ? DBNull.Value : objValue;
                            }
                        }
                        dt.Rows.Add(newRow);
                    }
                }

                return dt;
            }

  • 相关阅读:
    [转]SIFT特征提取分析
    OSGEARTH三维地形开源项目
    使用C#改变鼠标的指针形状
    检测到 LoaderLock:DLL"XXXX"正试图在OS加载程序锁内执行
    未能加载文件或程序集“XXXXX”或它的某一个依赖项。试图加载格式不正确的程序。
    未能进入中断模式,原因如下:源文件“XXXXXX”不属于正在调试的项目。
    C# 版本的 计时器类:精确到微秒 秒后保留一位小数 支持年月日时分秒带单位的输出
    OpenGL2.0及以上版本中glm,glut,glew,glfw,mesa等部件的关系
    OpenGL 4.3配置教程
    ubuntu maven环境安装配置
  • 原文地址:https://www.cnblogs.com/dullbaby/p/2949958.html
Copyright © 2011-2022 走看看