How to Convert DataTable to List In ASP.NET MVC

In this article, we will learn how to convert a DataTable to a List in ASP.NET MVC.

Now first create ASP.NET MVC Project

Then create model and add below code.

public class Employee
{
    public int EmployeeId { get; set; }
    public string EmployeeName { get; set; }
    public int Age { get; set; }
    public string Address { get; set; }     
    public string PhoneNo { get; set; }
}

1) Convert DataTable to List Using Linq

public ActionResult EmployeeListUsingLinq()
{
    DataTable dt = new DataTable("Employee");
    dt.Columns.Add("EmployeeId", typeof(Int32));
    dt.Columns.Add("EmployeeName", typeof(string));
    dt.Columns.Add("Age", typeof(Int32));
    dt.Columns.Add("Address", typeof(string));
    dt.Columns.Add("PhoneNo", typeof(string));

    dt.Rows.Add(1, "Priyank", 22, "Surat", "1111111111");
    dt.Rows.Add(2, "Raj", 18, "Mumbai", "2222222222");
    dt.Rows.Add(3, "Rinkesh", 23, "Pune", "3333333333");
    dt.Rows.Add(4, "Dhaval", 21, "Baroda", "4444444444");

    List<Employee> EmployeeList = new List<Employee>();
    EmployeeList = (from DataRow dr in dt.Rows
                   select new Employee()
                   {
                       EmployeeId = Convert.ToInt32(dr["EmployeeId"]),
                       EmployeeName = dr["EmployeeName"].ToString(),
                       Age = Convert.ToInt32(dr["Age"]),
                       Address = dr["Address"].ToString(),
                       PhoneNo = dr["PhoneNo"].ToString()
                   }).ToList();

    return View(EmployeeList);
}

2) Convert DataTable to List Using a Loop

public ActionResult EmployeeListUsingLoop()
{
    DataTable dt = new DataTable("Employee");
    dt.Columns.Add("EmployeeId", typeof(Int32));
    dt.Columns.Add("EmployeeName", typeof(string));
    dt.Columns.Add("Age", typeof(Int32));
    dt.Columns.Add("Address", typeof(string));
    dt.Columns.Add("PhoneNo", typeof(string));

    dt.Rows.Add(1, "Priyank", 22, "Surat", "1111111111");
    dt.Rows.Add(2, "Raj", 18, "Mumbai", "2222222222");
    dt.Rows.Add(3, "Rinkesh", 23, "Pune", "3333333333");
    dt.Rows.Add(4, "Dhaval", 21, "Baroda", "4444444444");

    List<Employee> EmployeeList = new List<Employee>();
    for (int i = 0; i < dt.Rows.Count; i++)
    {
        Employee employee = new Employee();
        employee.EmployeeId = Convert.ToInt32(dt.Rows[i]["EmployeeId"]);
        employee.EmployeeName = dt.Rows[i]["EmployeeName"].ToString();
        employee.Age = Convert.ToInt32(dt.Rows[i]["Age"]);
        employee.Address = dt.Rows[i]["Address"].ToString();
        employee.PhoneNo = dt.Rows[i]["PhoneNo"].ToString();
        EmployeeList.Add(employee);
    }

    return View(EmployeeList);
}

Output :

Employee List

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories