DataTable to List<object>

后端 未结 7 972
误落风尘
误落风尘 2020-12-03 09:05

How do I take a DataTable and convert it to a List?

I\'ve included some code below in both C# and VB.NET, the issue with both of these is that we create a new object

7条回答
  •  一向
    一向 (楼主)
    2020-12-03 09:35

    No sure if this is what your looking for but you could try something like this.

        public class Category
    {
        private int _Id;
        public int Id
        {
            get { return _Id; }
            set { _Id = value; }
        }
    
        private string _Name = null;
        public string Name
        {
            get { return _Name; }
            set { _Name = value; }
        }
    
        public Category()
        {}
    
        public static List GetCategories()
        {
            List currentCategories = new List();
    
            DbCommand comm = GenericDataAccess.CreateTextCommand();
            comm.CommandText = "SELECT Id, Name FROM Categories Order By Name";
            DataTable table = GenericDataAccess.ExecuteSelectCommand(comm);
    
            foreach (DataRow row in table.Rows)
            {
                Category cat = new Category();
                cat.Id = int.Parse(row["Id"].ToString());
                cat.Name = row["Name"].ToString();
                currentCategories.Add(cat);
            }
            return currentCategories;
        }
    }
    

    This is what I have done so hope this helps. Not sure if it is the right way to do it but it works for what we needed it for.

提交回复
热议问题