DataTable to List<object>
I have another approach that might be worth taking a look at. It's a helper method. Create a custom class file named CollectionHelper:
public static IList<T> ConvertTo<T>(DataTable table)
{
if (table == null)
return null;
List<DataRow> rows = new List<DataRow>();
foreach (DataRow row in table.Rows)
rows.Add(row);
return ConvertTo<T>(rows);
}
Imagine you want to get a list of customers. Now you'll have the following caller:
List<Customer> myList = (List<Customer>)CollectionHelper.ConvertTo<Customer>(table);
The attributes you have in your DataTable must match your Customer class (fields like Name, Address, Telephone).
I hope it helps!
For who are willing to know why to use lists instead of DataTables: link text
The full sample:
http://lozanotek.com/blog/archive/2007/05/09/Converting_Custom_Collections_To_and_From_DataTable.aspx
No, creating a list is not costly. Compared to creating the data table and fetching the data from the database, it's very cheap.
You can make it even cheaper by creating the list after populating the table, so that you can set the initial capacity to the number of rows that you will put in it:
IList<INote> notes = new List<INote>(table.Rows.Count);