How do you convert a DataTable into a generic list?

前端 未结 27 2547
后悔当初
后悔当初 2020-11-22 17:04

Currently, I\'m using:

DataTable dt = CreateDataTableInSomeWay();

List list = new List(); 
foreach (DataRow dr in dt.Rows)
{
          


        
相关标签:
27条回答
  • 2020-11-22 17:36
    List<Employee> emp = new List<Employee>();
    
    //Maintaining DataTable on ViewState
    //For Demo only
    
    DataTable dt = ViewState["CurrentEmp"] as DataTable;
    
    //read data from DataTable 
    //using lamdaexpression
    
    
    emp = (from DataRow row in dt.Rows
    
       select new Employee
       {
           _FirstName = row["FirstName"].ToString(),
           _LastName = row["Last_Name"].ToString()
    
       }).ToList();
    
    0 讨论(0)
  • 2020-11-22 17:36

    A more 'magic' way, and doesn't need .NET 3.5.

    If, for example, DBDatatable was returning a single column of Guids (uniqueidentifier in SQL) then you could use:

    Dim gList As New List(Of Guid)
    gList.AddRange(DirectCast(DBDataTable.Select(), IEnumerable(Of Guid)))
    
    0 讨论(0)
  • 2020-11-22 17:36

    To assign the DataTable rows to the generic List of class

      List<Candidate> temp = new List<Candidate>();//List that holds the Candidate Class,
        //Note:The Candidate class contains RollNo,Name and Department
        //tb is DataTable
        temp = (from DataRow dr in tb.Rows
                            select new Candidate()
                            {
                                RollNO = Convert.ToInt32(dr["RollNO"]),
                                Name = dr["Name"].ToString(),
                                Department = dr["Department"].ToString(),
    
                            }).ToList();
    
    0 讨论(0)
  • 2020-11-22 17:37

    Output

    public class ModelUser
    {
        #region Model
    
        private string _username;
        private string _userpassword;
        private string _useremail;
        private int _userid;
    
        /// <summary>
        /// 
        /// </summary>
        public int userid
        {
            set { _userid = value; }
            get { return _userid; }
        }
    
    
        /// <summary>
        /// 
        /// </summary>
    
        public string username
        {
            set { _username = value; }
            get { return _username; }
        }
    
        /// <summary>
        /// 
        /// </summary>
        public string useremail
        {
            set { _useremail = value; }
            get { return _useremail; }
        }
    
        /// <summary>
        /// 
        /// </summary>
        public string userpassword
        {
            set { _userpassword = value; }
            get { return _userpassword; }
        }
        #endregion Model
    }
    
    public List<ModelUser> DataTableToList(DataTable dt)
    {
        List<ModelUser> modelList = new List<ModelUser>();
        int rowsCount = dt.Rows.Count;
        if (rowsCount > 0)
        {
            ModelUser model;
            for (int n = 0; n < rowsCount; n++)
            {
                model = new ModelUser();
    
                model.userid = (int)dt.Rows[n]["userid"];
                model.username = dt.Rows[n]["username"].ToString();
                model.useremail = dt.Rows[n]["useremail"].ToString();
                model.userpassword = dt.Rows[n]["userpassword"].ToString();
    
                modelList.Add(model);
            }
        }
        return modelList;
    }
    
    static DataTable GetTable()
    {
        // Here we create a DataTable with four columns.
        DataTable table = new DataTable();
        table.Columns.Add("userid", typeof(int));
        table.Columns.Add("username", typeof(string));
        table.Columns.Add("useremail", typeof(string));
        table.Columns.Add("userpassword", typeof(string));
    
        // Here we add five DataRows.
        table.Rows.Add(25, "Jame", "Jame@hotmail.com", DateTime.Now.ToString());
        table.Rows.Add(50, "luci", "luci@hotmail.com", DateTime.Now.ToString());
        table.Rows.Add(10, "Andrey", "Andrey@hotmail.com", DateTime.Now.ToString());
        table.Rows.Add(21, "Michael", "Michael@hotmail.com", DateTime.Now.ToString());
        table.Rows.Add(100, "Steven", "Steven@hotmail.com", DateTime.Now.ToString());
        return table;
    }
    
    protected void Page_Load(object sender, EventArgs e)
    {
        List<ModelUser> userList = new List<ModelUser>();
    
        DataTable dt = GetTable();
    
        userList = DataTableToList(dt);
    
        gv.DataSource = userList;
        gv.DataBind();
    }[enter image description here][1]
    

    </asp:GridView>
    </div>
    
    0 讨论(0)
  • 2020-11-22 17:37

    You can use a generic method like that for datatable to generic list

    public static List<T> DataTableToList<T>(this DataTable table) where T : class, new()
    {
        try
        {
            List<T> list = new List<T>();
    
            foreach (var row in table.AsEnumerable())
            {
                T obj = new T();
    
                foreach (var prop in obj.GetType().GetProperties())
                {
                    try
                    {
                        PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name);
                        if (propertyInfo.PropertyType.IsEnum)
                        {
                            propertyInfo.SetValue(obj, Enum.Parse(propertyInfo.PropertyType, row[prop.Name].ToString()));
                        }
                        else
                        {
                            propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null);
                        }                          
                    }
                    catch
                    {
                        continue;
                    }
                }
    
                list.Add(obj);
            }
    
            return list;
        }
        catch
        {
            return null;
        }
    }
    
    0 讨论(0)
  • 2020-11-22 17:42
    lPerson = dt.AsEnumerable().Select(s => new Person()
            {
                Name = s.Field<string>("Name"),
                SurName = s.Field<string>("SurName"),
                Age = s.Field<int>("Age"),
                InsertDate = s.Field<DateTime>("InsertDate")
            }).ToList();
    

    Link to working DotNetFiddle Example

    using System;
    using System.Collections.Generic;   
    using System.Data;
    using System.Linq;
    using System.Data.DataSetExtensions;
    
    public static void Main()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("Name", typeof(string));
        dt.Columns.Add("SurName", typeof(string));
        dt.Columns.Add("Age", typeof(int));
        dt.Columns.Add("InsertDate", typeof(DateTime));
    
        var row1= dt.NewRow();
        row1["Name"] = "Adam";
        row1["SurName"] = "Adam";
        row1["Age"] = 20;
        row1["InsertDate"] = new DateTime(2020, 1, 1);
        dt.Rows.Add(row1);
    
        var row2 = dt.NewRow();
        row2["Name"] = "John";
        row2["SurName"] = "Smith";
        row2["Age"] = 25;
        row2["InsertDate"] = new DateTime(2020, 3, 12);
        dt.Rows.Add(row2);
    
        var row3 = dt.NewRow();
        row3["Name"] = "Jack";
        row3["SurName"] = "Strong";
        row3["Age"] = 32;
        row3["InsertDate"] = new DateTime(2020, 5, 20);
        dt.Rows.Add(row3);
    
        List<Person> lPerson = new List<Person>();
        lPerson = dt.AsEnumerable().Select(s => new Person()
        {
            Name = s.Field<string>("Name"),
            SurName = s.Field<string>("SurName"),
            Age = s.Field<int>("Age"),
            InsertDate = s.Field<DateTime>("InsertDate")
        }).ToList();
    
        foreach(Person pers in lPerson)
        {
            Console.WriteLine("{0} {1} {2} {3}", pers.Name, pers.SurName, pers.Age, pers.InsertDate);
        }
    }   
    
    public class Person
    {
        public string Name { get; set; }
        public string SurName { get; set; }
        public int Age { get; set; }
        public DateTime InsertDate { get; set; }
    }
    

    }

    0 讨论(0)
提交回复
热议问题