Showing posts with label using reflection datatable to list; datatable to list using reflection. Show all posts
Showing posts with label using reflection datatable to list; datatable to list using reflection. Show all posts

Friday, May 20, 2011

Convert datatable into list using reflection

Using reflection we can convert the datatable into strongly typed collection. I'll prefer list as a collection.

Let's suppose I have a class of Emp and I have put two fields in it. 
class Emp{ string Id {get; set;} string Name{get; set;}}
Now, to convert datatable into any class, Ofcourse we'll have to use Generic template that will find the type of the class. 
We are creating a class that will convert Datatable into strongly typed list. 

This is the declaration of a class where we will refer any business class as a 'T' and that 'T' type should have a constructor with no arguments. We are ensuring in the where. 
public class DatatableToListMapper : where T : new()
We will create a method ConvertDataTableIntoList where Datatable will be passed as an argument and this method will return List of type T.
Here's the signature of the method.
List ConvertDataTableIntoList(DataTable dt)
// create list of type T.
List objT = new List();
Now we will fetch every row from the DataTable.
foreach(DataRow dr in dt.Rows)
Now we will get the properties of the T class using the method typeof(T).GetProperties() and will retrieve every property using loop. Create an object of type T.

e.g. 
T obj = new T();
foreach(var property in typeof(T).GetProperties()){
property.SetValue(obj, dr[property.Name], null); /// Setting the property value in the object obj.
}
//Add this object in a 
objT.Add(obj);

At last return the object of list after conversion. I'll share the code in the next post where the mapping can be user defined using a Dictionary collection.


return objT;