Minifycode 2021-10-03 Viewed 1.3K times LINQ

In this article, you will learn how to Convert Datatable to List Example using LINQ in C#

 

In this article, you will how to convert datatable to list example using LINQ in C#

 

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

public partial class ConvertDatatableToList : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindUserDetails();
        }
    }
    private void BindUserDetails()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("UserId", typeof(Int32));
        dt.Columns.Add("UserName", typeof(string));
        dt.Columns.Add("RollNo", typeof(string));
        dt.Rows.Add(1, "a", "123");
        dt.Rows.Add(2, "b", "124");
        dt.Rows.Add(3, "c", "125");
        List<UserDetails> list = new List<UserDetails>();

        list = (from DataRow row in dt.Rows

                select new UserDetails()
                {
                    UserId = row["UserId"].ToString(),
                    UserName = row["UserName"].ToString(),
                    Education = row["RollNo"].ToString()
                }).ToList();

        gdvuserdetails.DataSource = list;
        gdvuserdetails.DataBind();
    }
    public class UserDetails
    {
        public string UserId { get; set; }
        public string UserName { get; set; }
        public string RollNo{ get; set; }
    }
}

 

<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="gdvuserdetails" runat="server">
</asp:GridView>
</div>
</form>
</body>
</html>

Convert Datatable to List Example using LINQ in C#
minify code