Fastest way to convert datatable to generic list

后端 未结 6 720
逝去的感伤
逝去的感伤 2020-12-01 15:30

I have a data tier select method that returns a datatable. It\'s called from a business tier method that should then return a strongly typed generic List.

What I wa

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 15:52

    Just to provide some more user - friendliness to Mark's answer in a simple console app :

    class Program
    {
        static void Main(string[] args)
        {
            //define a DataTable obj
            DataTable table = new DataTable
            {
                Columns = {
                {"Foo", typeof(int)},
                {"Bar", typeof(string)}
             }
            };
            //populate it the DataTable 
            for (int i = 0; i < 3; i++)
            {
                table.Rows.Add(i, "Row " + i);
            }
    
            List listWithTypedObjects= new List(table.Rows.Count);
            foreach (DataRow row in table.Rows)
            {
                listWithTypedObjects.Add(new MyType((int)row[0], (string)row[1]));
            }
    
            Console.WriteLine(" PRINTING THE POPULATED LIST ");
            foreach (MyType objMyType in listWithTypedObjects)
            {
                Console.Write(" I have object of the type " + objMyType.ToString() + " => " );
                Console.Write(" with Prop1OfTypeInt " + objMyType.Prop1OfTypeInt.ToString() + " , ");
                Console.WriteLine(" with Prop1OfTypeInt " + objMyType.Prop2OfTypeString.ToString() + "  "); 
            }
    
            Console.WriteLine(" \n \n \n HIT A KEY TO EXIT THE PROGRAM ");
            Console.ReadKey();
        }
    }
    
    class MyType {
    
        public int Prop1OfTypeInt { get; set; }
        public string Prop2OfTypeString { get; set; } 
    
        /// 
        /// Note the order of the passed parameters is important !!!
        /// 
        public MyType( int prop1OfTypeInt , string prop2OfTypeString)
        {
            this.Prop1OfTypeInt = prop1OfTypeInt;
            this.Prop2OfTypeString = prop2OfTypeString; 
    
        }
    }
    

提交回复
热议问题