How convert DataTable to List by extension methods - Online Free Computer Tutorials.

'Software Development, Games Development, Mobile Development, iOS Development, Android Development, Window Phone Development. Dot Net, Window Services,WCF Services, Web Services, MVC, MySQL, SQL Server and Oracle Tutorials, Articles and their Resources

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;
        }



No comments:

Post a Comment