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.
string
Comment {
get
;
set
; }
4.
Commentedby {
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.
strpath = System.IO.Path.Combine(AppDomain.CurrentDomain.GetData(“DataDirectory”).ToString(), “Testimonials.xml”);
04.
DataSet ds =
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
11.
12.
Comment = r.Field<
>(“Comment”),
13.
Commentedby = r.Field<
>(“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
Maheshkumar S Tiwari edited Original. Comment: Added tags and minor edit
Helpfull article thanks :)