Search This Blog


Monday, January 23, 2012

Convert dataset into List using reflection in C#

This article , I am going to explain you how to convert a dataset or datatable into a generic list of your class property or you may say another way out for entity frame work design of object to database relation mapping and using LINQ on the item collection list
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);
            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()
                 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......

No comments :

Post a Comment