Wednesday, April 26, 2017

Convert Generic List to DataTable using Extension Method

If you want to convert a generic list to DataTable you can use the below extension method for IList<T>

Let's say you have the following list with you 

List<someClass> someClassObjectList = new List<someClass>();

DataTable someDataTable = new DataTable();

and you want to convert the someClassObjectList to DataTable object 

The possible solution you end up by writing a convert or translate method which will convert the each and every property and assigns to DataTable object, something looks like this




By using the above code also your job will get done, but what if your class has 100 properties and what if you want convert lots of different generic lists like this. You can't write the different method for the different generic list, and you don't have the patience to list the 100 properties like above. 

Now what do, you can write a single extension method.

Create a static class in your project with some name like "Extensions" and write the below code in that class

Now in your actual class  wherever you want to convert the generic list to DataTable write code like below

var someDataTable  = someClassObjectList .ToDataTable<someClass>();

using a single method you can convert any generic list to DataTable.

var anotherDataTable  = anotherClassObjectList .ToDataTable<anotherClass>();

var oneMoreDataTable  = oneMoreClassObjectList .ToDataTable<oneMoreClass>();
.
.
.

Write once use anywhere.