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;


Thursday, May 19, 2011

Convert Datatable into collection using LINQ

We can create the anonymous type from the data table but If we are interested to convert data table into strongly typed collection like List of Emp type from the datatable. Below is the code snippet.

    public class Emp
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

                DataTable dt = new DataTable();
                dt.Columns.Add("EmpId");
                dt.Columns.Add("EmpName");
                dt.Rows.Add("1", "Sohail");
                dt.Rows.Add("2", "Yasir");
                dt.Rows.Add("3", "Shahid");
Convert data type into AsEnumerable and then select the rows from the table and put one by one field in the emp object.
             List emp = new List();
             var result = from p in dt.AsEnumerable()
             select new Emp
             {
                     Id = int.Parse(p[0].ToString()),
                     Name = p[1].ToString()
             };

          After all, convert the result into List of Emp type.
           emp = result.ToList();       
           foreach (var row in emp)
           Console.WriteLine("{0}, {1}", row.Id, row.Name);