How to convert datatable to list in c#

How to convert datatable to list in c#

Convert a DataTable to a List in C#. There are the following 3 ways to convert a DataTable to a List.

  1. Using a Loop.
  2. Using LINQ.
  3. Using a Generic Method.
public class Student  
    public string Address { get; set; }  
    public string MobileNo { get; set; }  
DataTable dt = new DataTable("Student");  
dt.Columns.Add("Address", typeof(string));  
dt.Columns.Add("MobileNo", typeof(string));  
dt.Rows.Add(1, "Ram", "Punjab", "0987678989");  
dt.Rows.Add(2, "Shyam", "Delhi", "9888888888");

It is a generic method, it converts all types of list into DataTable. <T> defines the type of list

using System.ComponentModel;
private DataTable ConvertToDataTable<T>(IList<T> list)
    Type entityType = typeof(T);
    DataTable table = new DataTable();
    PropertyDescriptorCollection properties =
    foreach (PropertyDescriptor prop in properties)
        table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
    foreach (T item in list)
        DataRow row = table.NewRow();
        foreach (PropertyDescriptor prop in properties)
            row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
    return table;

Using LINQ lambda expression

List<UserDetails> list=new List<UserDetails>();
list = (from DataRow row in dt.Rows

select new UserDetails()
Id = row["Id"].ToString(),
Name = row["Name"].ToString(),
Age = row["Age"].ToString()
<html xmlns="">
<head runat="server">
<title>Convert Datatable to List in c#</title>
<form id="form1" runat="server">
<asp:GridView ID="gdvLst" runat="server">