Thursday, January 5, 2012

How convert DataTable to List by extension methods


In this post i will explain how can convert a datatable to LIST<T> in c# by using extension methods.
Below is the Public extension method which will convert datatable to LIST<T>


   public static IList<T> ConvertToList<T>(this DataTable dt) where T : classnew()
        {
            if (dt == null || dt.Rows.Count == 0) return null;
            IList<T> list = new List<T>();
            foreach (DataRow row in dt.Rows)
            {
                T obj = ConvertDataRowToEntity<T>(row);
                list.Add(obj);
            }
            return list;
        }


 This method will internally called below method 

   private static T ConvertDataRowToEntity<T>(DataRow row) where T : classnew()
        {
            Type objType = typeof(T);
            T obj = Activator.CreateInstance<T>(); 
            foreach (DataColumn column in row.Table.Columns)
            {
                 PropertyInfo property =
                    objType.GetProperty(column.ColumnName,
                    BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
                if (property == null || !property.CanWrite)
                {
                   
                    continue
                }
                object value = row[column.ColumnName];
                if (value == DBNull.Value) value = null;
                property.SetValue(obj, value, null);
                Debug.WriteLine("obj." + property.Name + " = row[\"" + column.ColumnName +"\"];");
            }
            return obj;
        }



LinkWithin

LinkWithin

Like Us On Facebook and Receive All Updates!

You can also receive Free Email Updates:

Powered By Tutorails