Minifycode 2020-02-02 Viewed 3.6K times C#

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

  1. Using LINQ.
  2. Using a Loop.
  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));  
    //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>

how to convert datatable to list in c#
C# is a programming language developed by Microsoft that runs on the .NET Framework. C# is used to develop web, desktop, mobile, games and much more application. C# is a object-oriented programming language developed by Microsoft within its .NET Framework. Led by Anders Hejlsberg, your basic C# programming and will also take you through various advanced concepts related to C# programming language. C# such as control statements, objects and classes, inheritance, constructor, destructor, this, static, sealed, polymorphism, abstraction, abstract class, interface, File IO, Collections, namespace, encapsulation, properties, indexer, arrays, strings, regex, exception handling, multithreading etc. For example... using System; namespace MinifyCode { class Program { static void Main(string[] args) { Console.WriteLine("Hello Minify Code"); } } } Output: Hello Minify Code In this article you will learn, what is server side controls. We will discuss each of these objects in due time. In this tutorial we will explore the Server object, the Request object, and the Response object. Session Application Cache Request Response Server User Trace Server Object The Server object in Asp.NET is an instance of the System.Web.HttpServerUtility class. The HttpServerUtility class provides numerous properties and methods to perform many type of jobs. Methods and Properties of the Server object The methods and properties of the HttpServerUtility class are exposed through the intrinsic Server object provided by ASP.NET. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Optimization; using System.Web.Routing; using System.Web.Security; using System.Web.SessionState; using System.Data.Entity; namespace minifycode { public class Global : HttpApplication { void Application_Start(object sender, EventArgs e) { // Code that runs on application startup RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); // Initialize the product database. Database.SetInitializer(new ProductDatabaseInitializer()); // Create custom role and user. RoleActions roleActions = new RoleActions(); roleActions.AddUserAndRole(); // Add Routes. RegisterCustomRoutes(RouteTable.Routes); } void RegisterCustomRoutes(RouteCollection routes) { routes.MapPageRoute( "ProductsCategoryRoute", "Category/{categoryName}", "~/ProductList.aspx" ); routes.MapPageRoute( "ProductNameRoute", "Product/{productName}", "~/ProductDetails.aspx" ); } } }