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
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 ConvertTo(DataTable table)
{
if (table == null)
return null;
List rows = new List();
foreach (DataRow row in table.Rows)
rows.Add(row);
return ConvertTo(rows);
}
Imagine you want to get a list of customers. Now you'll have the following caller:
List myList = (List)CollectionHelper.ConvertTo(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