Probably the best way is not to read datatable at first:
var dr = new DataReader(....) // Fill in what is needed, can't remember offhand while(dr.Next()) { persons.Add( new Person() { Name = (string) r["Name"], Age = (int) r["Age"] } ); }
Caution You want to quickly close the DataReader / connection, do not do much processing. The above code is more efficient than using a DataTable as an intermediary.
But if you want to use the data table first, you can use LINQ:
var list = dt.AsEnumerable().Select(r => new Person() { Name = (string) r["Name"], Age = (int) r["Age"] } ).ToList()
or just enter dt.Rows and create a new person and add him to the list
You should also use the Use () operators around your connection and reading .
source share