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; } }
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; }
Post a Comment