zoukankan      html  css  js  c++  java
  • C# 将 DataTable 转 List<T>、首行转 T

    1. 添加帮助类 TypeChange.cs

    public static class TypeChange<T> where T : new()
    {
        /// <summary>
        /// 将DataTable转换为实体列表
        /// </summary>
        /// <param name="dt">待转换的DataTable</param>
        /// <returns></returns>
        public static List<T> ChangeToList(DataTable dt)
        {
            // 定义集合  
            var list = new List<T>();
    
            if (0 == dt.Rows.Count)
            {
                return list;
            }
    
            // 获得此模型的可写公共属性  
            IEnumerable<PropertyInfo> propertys = new T().GetType().GetProperties().Where(u => u.CanWrite);
            list = ChangeToEntity(dt, propertys);
            return list;
        }
    
        /// <summary>
        /// 将DataTable的首行转换为实体
        /// </summary>
        /// <param name="dt">待转换的DataTable</param>
        /// <returns></returns>
        public static T ChangeToEntity(DataTable dt)
        {
            DataTable dtTable = dt.Clone();
            dtTable.Rows.Add(dt.Rows[0].ItemArray);
            return ChangeToList(dtTable)[0];
        }
    
        private static List<T> ChangeToEntity(DataTable dt, IEnumerable<PropertyInfo> propertys)
        {
            var list = new List<T>();
            //遍历DataTable中所有的数据行  
            foreach (DataRow dr in dt.Rows)
            {
                var entity = new T();
    
                //遍历该对象的所有属性  
                foreach (PropertyInfo p in propertys)
                {
                    //将属性名称赋值给临时变量
                    string tmpName = p.Name;
    
                    //检查DataTable是否包含此列(列名==对象的属性名)    
                    if (!dt.Columns.Contains(tmpName)) continue;
                    //取值  
                    object value = dr[tmpName];
                    //如果非空,则赋给对象的属性  
                    if (value != DBNull.Value)
                    {
                        p.SetValue(entity, value, null);
                    }
                }
                //对象添加到泛型集合中  
                list.Add(entity);
            }
            return list;
        }
    }

    2. 创建实体类

    public class User {
        public string ID { get; set; }
        public string Name { get; set; }
    }

    3. 实现

    DataTable dt = new DataTable();
    dt.Columns.Add("ID");
    dt.Columns.Add("Name");
    dt.Rows.Add("1", "哈哈哈");
    dt.Rows.Add("2", "嘎嘎");
    List<User> list = TypeChange<User>.ChangeToList(dt);
  • 相关阅读:
    Quartz.Net在windows服务中的使用
    mysql之group by,order by
    mysql之select,insert,delete,update
    win8.1安装VMware Error:This product may not be installed on a comuputer that has Microsoft HyperV installed
    mysql之创建数据库,创建数据表
    深入浅出空间索引:2
    地图点聚合优化方案
    地理围栏算法解析
    GeoHash核心原理解析
    Mongodb地理空间索引
  • 原文地址:https://www.cnblogs.com/Allofus/p/15040290.html
Copyright © 2011-2022 走看看