• [工具类]泛型集合转换为DataTable


    写在前面

    在实际项目中,用到了将集合转换为DataTable,就试着封装了一个方法,记录一下。

    代码

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Linq;
    using System.Reflection;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Wolfy.List2DataTable
    {
        class Program
        {
            static void Main(string[] args)
            {
                List<Person> lst = new List<Person>() 
                { 
                    new Person(){ ID=1, Gender=false, Name="wolfy1"},
                     new Person(){ ID=2, Gender=false, Name="wolfy2"},
                      new Person(){ ID=3, Gender=false, Name="wolfy3"},
                       new Person(){ ID=4, Gender=false, Name="wolfy4"},
                        new Person(){ ID=5, Gender=false, Name="wolfy5"},
                };
                DataTable dt = List2DataTable<Person>(lst);
                Console.WriteLine("转换结束");
                Console.Read();
            }
            /// <summary>
            /// 将泛型集合转换为datatable
            /// </summary>
            /// <typeparam name="TEntity"></typeparam>
            /// <param name="entities"></param>
            /// <returns></returns>
            static DataTable List2DataTable<TEntity>(List<TEntity> entities)
            {
                if (entities == null)
                {
                    throw new ArgumentNullException("转换的集合为空");
                }
                Type type = typeof(TEntity);
                PropertyInfo[] properties = type.GetProperties();
                DataTable dt = new DataTable(type.Name);
                foreach (var item in properties)
                {
                    dt.Columns.Add(new DataColumn(item.Name) { DataType = item.PropertyType });
                }
                foreach (var item in entities)
                {
                    DataRow row = dt.NewRow();
                    foreach (var property in properties)
                    {
                        row[property.Name] = property.GetValue(item);
                    }
                    dt.Rows.Add(row);
                }
                return dt;
            }
        }
        public class Person
        {
            public int ID { set; get; }
            public string Name { set; get; }
            public bool Gender { set; get; }
        }
    }

    测试结果:

  • 相关阅读:
    jdk7_ConcurrentHashMap 图示
    Teradata 日期函数
    Teradata正则表达式
    Teradata sql去除字段中的字母/数字
    sql查询连续3天有交易记录的客户
    批量生成sql查询语句
    sql查询字段中是否含有字母/数字/符号
    sql查询每个人最新的2个电话号码
    python连接Teradata数据库
    dos命令获取文件行数
  • 原文地址:https://www.cnblogs.com/wolf-sun/p/4593064.html
Copyright © 2020-2023  润新知