C# – Convert DataTable to Generic List

Updated on     Kisan Patel

This tutorial describes various ways to convert a DataTable to a List in C#. There are the mainly 3 ways to convert a DataTable to a List in C#.

For this example I am creating a simple Users class like:

public class Users
{
      public int UserId { get; set; }
      public string UserName { get; set; }
      public string Email { get; set; }
      public string Name { get; set; }
}

Method 1:

Using LINQ lambda expression:

List<Users> list = new List<Users>();
list = (from DataRow row in dt.Rows
         select new Users()
         {
              UserId = Convert.ToInt32(row["UserId"]),
              UserName = row["UserName"].ToString(),
              Email = row["Email"].ToString(),
              Name = Convert.ToString(row["Name"])
       }).ToList();

Method 2:

Using foreach loop:

List<Users> list=new List<Users>();
foreach (DataRow row in dt.Rows)
{
       Users user = new Users();
       user.UserId = Convert.ToInt32(row["UserId"]);
       user.UserName = row["UserName"].ToString();
       user.Email = row["Email"].ToString();
       user.Name = Convert.ToString(row["Name"]);
       list.Add(user);
}

C#

Leave a Reply