Convert DataTable To Generic List Using AsEnumerable In ASP.NET MVC

Sometimes we need to work with a generic list, which will be generated from a model class. Suppose we are getting data from a database in a data table and thinking of binding a view from a model class generic list, then first we need to convert the data table into a generic list .

Related article

So let us see how we can convert a datatable to a generic list using AsEnumerable.
Suppose the model class is EmpModel.cs as below.

public class EmpModel
        [Display(Name = "Id")]
        public int Empid { get; set; }
        [Required(ErrorMessage = "First name is required.")]
        public string Name { get; set; }
        [Required(ErrorMessage = "City is required.")]
        public string City { get; set; }

        [Required(ErrorMessage = "Address is required.")]
        public string Address { get; set; }


The following is the conversion logic

public List<EmpModel> GetAllEmployees()
            List<EmpModel> EmpList =new List<EmpModel>();
            SqlCommand com = new SqlCommand("GetEmployees", con);
            com.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter(com);
            DataTable dt = new DataTable();
            //Bind EmpModel generic list using AsEnumerable 
           List<DataRow> list = dt.AsEnumerable().ToList();
            foreach (var item in list)

                   new EmpModel
                       Empid = Convert.ToInt32(item["Id"]),
                       Name = Convert.ToString(item["Name"]),
                       City = Convert.ToString(item["City"]),
                       Address = Convert.ToString(item["Address"])


            return EmpList;



I hope this article is useful for all readers. If you have any suggestions, then please contact me.

Post a Comment

Protected by Copyscape
Copyright © Compilemode