Sometimes 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 articles to learn more about them
So let us see how we can Convert DataTable To Generic List Using AsEnumerable
There are many ways to achieve it .refer previous articles to learn more about them
So let us see how we can Convert DataTable To 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; } }
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 AsEnumerable List<DataRow> list = dt.AsEnumerable().ToList(); foreach (var item in list) { EmpList.Add( new EmpModel { Empid = Convert.ToInt32(item["Id"]), Name = Convert.ToString(item["Name"]), City = Convert.ToString(item["City"]), Address = Convert.ToString(item["Address"]) }); } return EmpList; }
Summary
I hope this article is useful for all readers. If you have any suggestion then please contact me.
Post a Comment