Sai Stuff to Developers

May 3, 2012

Converting DataTable to a List of Entity Object

Filed under: DotNet,LINQ — tosaik @ 12:30 pm
Tags: , , , , ,

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.

 public class Testimonial
    {
        public string Comment { get; set; }
        public string Commentedby { get; set; }
    }

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

List<Testimonial> lstTestimonial = new List<Testimonial>();

 string strpath = System.IO.Path.Combine(AppDomain.CurrentDomain.GetData(“DataDirectory”).ToString(), “Testimonials.xml”);
            DataSet ds = new DataSet();
            ds.ReadXml(strpath);

            if (ds != null && ds.Tables.Count > 0)
            {
                lstTestimonial = (from r in ds.Tables[0].AsEnumerable()
                                  select new Testimonial
                                  {
                                      Comment = r.Field<string>(“Comment”),
                                      Commentedby = r.Field<string>(“Commentedby”)
                                  }).ToList<Testimonial>();
            }

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 🙂

 

 

Blog at WordPress.com.