Convert DataTable To Generic List Using LINQ C#

In this article, we will learn how to convert Data Table to Generic list using the LINQ C#. Let's create the property class which stores the Data Table into the generic list.

EmpModel.cs

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; }

    }

Create the GetAllEmployees() method to convert the Data Table into the generic list and return the records in the list.

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 dataRow 
            foreach (DataRow dr in dt.Rows)
            {

                EmpList.Add(

                    new EmpModel {

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

                    }
                    
                    
                    );
            }

            return EmpList;

        }

I hope from the preceding example you have learned how to convert the Data Table to a generic list using the LINQ.

Related Articles

Post a Comment

www.CodeNirvana.in

Protected by Copyscape
Copyright © Compilemode