Converting DataTable to a List of Entity Object

Recently some one asked me how should I need to convert a DataTable to an List of Entity Object. Let me Explain in detail below…

Let say we have following Entity Class called Testimonial with two properties i.e.., Comment and Commentedby here Comment is the property where we have the actual comment by the User and Commentedby is the property to store the name of the User who commented it. 

1.public class  Testimonial
2.   {
3.       public string  Comment { get; set; }
4.       public string  Commentedby { get; set; }
5.   }

Now we need to get these Testimonial data from data source it may be from Database / XML file / CSV File etc.., we use XML file for this example . Now using linq we Enumerate the collection of dataRows in the datatable and create a list of Testimonials as shown below

01.List<Testimonial> lstTestimonial = new  List<Testimonial>();
02. 
03. string strpath = System.IO.Path.Combine(AppDomain.CurrentDomain.GetData(“DataDirectory”).ToString(), “Testimonials.xml”);
04.            DataSet ds = new  DataSet();
05.            ds.ReadXml(strpath);
06. 
07.            if (ds != null && ds.Tables.Count > 0)
08.            {
09.                lstTestimonial = (from r in  ds.Tables[0].AsEnumerable()
10.                                  select new  Testimonial
11.                                  {
12.                                      Comment = r.Field<string>(“Comment”),
13.                                      Commentedby = r.Field<string>(“Commentedby”)
14.                                  }).ToList<Testimonial>();
15.            }

Note this is the best way to convert because due to strong data-type using Field Method, we can rectify any type conversion issues at Compile time.

Hope this short explanation (due to insufficient time) Helps you… Please comment me in any case…

Happy Coding http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif?m=1129645325g