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

Many times in MVC we need to work with generic list which will be generated from model class , Suppose we are getting data from DataBase in DataTable and thinking to bind view from model class generic list then first we need to convert DataTable into generic list .
There are many ways to achieve it .refer previous article using is we loop through all data row
 Using above method its require huge amount of code and time to loop on each record so to overcome this problem we can use LINQ  to convert DataTable to Generic list . So let us see how we can achieve this
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; }

    }

 Now Class will be look like as follows


public List<EmpModel> GetAllEmployees()
        {
            connection();
            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();
            con.Open();
            da.Fill(dt);
            con.Close();
            //Bind EmpModel generic list using LINQ
           EmpList = (from DataRow dr in dt.Rows

                    select new EmpModel()
                    {
                        Empid = Convert.ToInt32(dr["Id"]),
                        Name = Convert.ToString(dr["Name"]),
                        City = Convert.ToString(dr["City"]),
                        Address = Convert.ToString(dr["Address"])
                    }).ToList();

            return EmpList;

        }

Please refer below similar article  as above
Summary
I hope this article is useful for all readers. If you have any suggestion then please contact me.

Post a Comment

www.CodeNirvana.in

Protected by Copyscape
Copyright © Compilemode