Welcome

Hello, Welcome to my blog. If you like feel free to refer others

Friday 20 January 2012

Convert your datatable to Collection of Generic List using Reflection

First you need to add the reference of the dll, "System.Reflection".

Then I have created a static function in my class that will convert my datatable to a generic list:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Reflection;
using System.Data;
using BusinessEntity;

namespace DataLayer.Entitymapper
{
    public static class EntityBinder
    {
        public static List<T> ToCollection<T>(this DataTable dt)
        {
            List<T> lst = new System.Collections.Generic.List<T>();
            Type tClass = typeof(T);
            PropertyInfo[] pClass = tClass.GetProperties();
            List<DataColumn> dc = dt.Columns.Cast<DataColumn>().ToList();
            T cn;
            foreach (DataRow item in dt.Rows)
            {
                cn = (T)Activator.CreateInstance(tClass);
                foreach (PropertyInfo pc in pClass)
                {
                 
                   DataColumn d = dc.Find(c => c.ColumnName == pc.Name);
                   if (d != null)
                   {
                       if (item[pc.Name] != DBNull.Value)
                       {
                           pc.SetValue(cn, (item[pc.Name]), null);
                       }
                   }  
                }
                lst.Add(cn);
            }
            return lst;
        }
    }
}


How to call: In my DataLayer Project I have created a class ResourceDAL.

Now i will create a function where i will pass the datatable and EntityBinder class ToCollection method will convert it into generic list of resources.

public List<ResourceBE> GetResource()
        {
             try
             {
                 DataSet DS = SqlHelper.ExecuteDataset(RTSSqlConnection.GetConnectionString, CommandType.StoredProcedure, "usp_GetResources");
                 DataTable dt = DS.Tables[0];

                 //return dt;
                 List<ResourceBE> listResource = EntityBinder.ToCollection<ResourceBE>(dt);
                 return listResource;
             }
            catch(Exception ex)
            {
                throw new Exception(ex.ToString());
            }
        }

So this function will return now a list of resources......

Happy learning............................:)












No comments:

Post a Comment