Search This Blog

Oct 21, 2012

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 IEnumerable<T>/ IQueryable<T> Interface. But DataTable does not
implement any of these. So we can not directly apply LINQ queries on a DataTable. 

But 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


No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...