Converting DataTable to a List of Entity Object

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>();
03. string strpath = System.IO.Path.Combine(AppDomain.CurrentDomain.GetData(“DataDirectory”).ToString(), “Testimonials.xml”);
04.            DataSet ds = new DataSet();
05.            ds.ReadXml(strpath);
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 :)

Leave a Comment
  • Please add 7 and 2 and type the answer here:
  • Post
Wiki - Revision Comment List(Revision Comment)
Sort by: Published Date | Most Recent | Most Useful
Page 1 of 1 (1 items)
Wikis - Comment List
Sort by: Published Date | Most Recent | Most Useful
Posting comments is temporarily disabled until 10:00am PST on Saturday, December 14th. Thank you for your patience.
  • Helpfull article thanks  :)

  • Maheshkumar S Tiwari edited Original. Comment: Added tags and minor edit

Page 1 of 1 (2 items)