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;
            }

  • 相关阅读:
    js函数——倒计时模块+无缝滚动
    一步步编写avalon组件02:分页组件
    mvc5+ef6+Bootstrap 项目心得--身份验证和权限管理
    只用css实现“每列四行,加载完一列后数据自动填充到下一列”的效果
    某考试 T1 arg
    vijos 2035 奇数偶数与绚丽多彩的数
    bzoj 5093: [Lydsy1711月赛]图的价值
    [HEOI2016/TJOI2016]求和
    [TJOI2015]概率论
    Codeforces 616 E Sum of Remainders
  • 原文地址:https://www.cnblogs.com/dullbaby/p/2949958.html
Copyright © 2011-2022 走看看