How to Convert DataTable to Collection of Custom Class object
Imagine you have a
DataTable with Records and you want to Convert that to a List of your Custom class objects ? how do you do that ?
The normal -straight forward way is to Loop through each
DataRow, Create a new instance of Custom class object, read the column values of the current row(iterator) in the loop and Set the Proerties of the object..
The below code shows looping the DataRows and Creating an object of our Custom Customer Class and Setting the Properties and Adding to the Collection of Customer objects.
We can avoid this handwritten ForEach loop by using some LINQ syntax. Generally LINQ queries works on data sources which implement the
IQueryable<T> Interface. But DataTable does not implement any of these. So we can not directly apply LINQ queries on a DataTable.
DataTable class has an extension method called
AsEnumerable which returns an IEnumerable collection of DataRow. So we can apply the
AsEnumerable function on a
DataTable and then play with some LINQ on the resulting collection.
So we can replace our previous version of code with the below one which make use of LINQ
For more information visit the msdn page http://msdn.microsoft.com/en-us/library/system.data.datatableextensions.asenumerable(v=vs.100).aspx.
Hope this helps you some day :)