Thursday, May 19, 2011

Convert Datatable into collection using LINQ

We can create the anonymous type from the data table but If we are interested to convert data table into strongly typed collection like List of Emp type from the datatable. Below is the code snippet.

    public class Emp
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

                DataTable dt = new DataTable();
                dt.Columns.Add("EmpId");
                dt.Columns.Add("EmpName");
                dt.Rows.Add("1", "Sohail");
                dt.Rows.Add("2", "Yasir");
                dt.Rows.Add("3", "Shahid");
Convert data type into AsEnumerable and then select the rows from the table and put one by one field in the emp object.
             List emp = new List();
             var result = from p in dt.AsEnumerable()
             select new Emp
             {
                     Id = int.Parse(p[0].ToString()),
                     Name = p[1].ToString()
             };

          After all, convert the result into List of Emp type.
           emp = result.ToList();       
           foreach (var row in emp)
           Console.WriteLine("{0}, {1}", row.Id, row.Name);

No comments:

Post a Comment