【问题标题】:Copy data from List<MyEntity> to DataTable object将数据从 List<MyEntity> 复制到 DataTable 对象
【发布时间】:2011-07-21 23:11:53
【问题描述】:

我有一个对象列表(其中对象是自定义实体类),我有一个 DataTable,其中包含与实体类的属性匹配的列。

有没有一种方法可以将列表中的数据项复制到数据表中,而无需遍历列表并手动将数据添加到数据表中。

这是我当前代码的示例(C# 4.0):

    void MergeData()
    {
        List<MyEntity> myEntities = GetEntities();

        // Create a DataTable based on the Properties of the MyEntity class
        Type entity = typeof(MyEntity);
        PropertyInfo[] properties = entity.GetProperties();
        DataTable dt = new DataTable();
        foreach (PropertyInfo pi in properties)
        {
            dt.Columns.Add(pi.Name);
        }

        // Here's where I loop through the List and fill the DataTable. 
        // Is there a way to fill the DataTable without looping through the List?    
        foreach (MyEntity e in myEntities)
        {
            DataRow dr = dt.NewRow();
            foreach (PropertyInfo pi in properties)
            {
                dr[pi.Name] = pi.GetValue(e, null);
            }
            dt.Rows.Add(dr);
        }
    }

通常,List 将包含大约 27k 项,所以我只是想知道是否有更清洁和/或更优化的方式将数据从我的 List 获取到 DataTable。

【问题讨论】:

    标签: c#-4.0 merge datatable generic-list


    【解决方案1】:

    如何让您的实体能够填充可以添加到数据表中的数据行。这样可以减少反射的使用。

    【讨论】:

    • 有趣的想法,但我无法对包含我们所有实体的程序集进行更改。
    • 你能继承它吗?这样你就可以保持实体清洁。或者编写辅助类,该类获取实体列表并通过直接访问实体的属性而不是使用反射为列分配值来返回填充的表。
    【解决方案2】:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    /// <summary>
    /// Summary description for UserBO
    /// </summary>
    public class UserBO
    {
        public UserBO()
        {
            //
            // TODO: Add constructor logic here
            //
        }
        private string _mUserName;
    
        public string UserName
        {
            get { return _mUserName; }
            set { _mUserName = value; }
        }
        private string _mPassword;
    
        public string Password
        {
            get { return _mPassword; }
            set { _mPassword = value; }
        }
        private int _mUserID;
    
        public int UserID
        {
            get { return _mUserID; }
            set { _mUserID = value; }
        }
    }
    
     IList<UserBO> objlistUserBo = new List<UserBO>();
     objlistUserBo = objUserFacade.Getuserinfo(objUSerBO);
    
                for (int iterator=0; iterator < objlistUserBo.Count; iterator++)
                {
                    objUSerBO = (UserBO)objlistUserBo[iterator];
                    string name = objUSerBO.UserName;
                    string pwd = objUSerBO.Password;
                }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-26
      • 2011-09-06
      • 2019-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-22
      • 1970-01-01
      相关资源
      最近更新 更多