Convert a DataTable to a List in C#. There are the following 3 ways to convert a DataTable to a List
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));
//Data
dt.Rows.Add(1, "Ram", "Punjab", "0987678");
dt.Rows.Add(2, "Abhi", "Delhi", "9999999999");
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 =
TypeDescriptor.GetProperties(entityType);
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;
table.Rows.Add(row);
}
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()
}).ToList();
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Convert Datatable to List in c#</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gdvLst" runat="server">
</asp:GridView>
</div>
</form>
</body>
</html>
2020-02-02