Skip to main content
Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet HTML/CSS Java JavaScript Node.js Python Python 3.11, Pandas, SQL
      Python 3.11, SQL Python 3.11, SQLAlchemy Python 3.11, SQLAlchemy, SQL Python 3.11, SQLite React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. C#
  4. How to Convert DataTable to List

How to Convert DataTable to List

Date- Jun 12,2022 Updated Jan 2026 7650 Free Download Pay & Download
C# AspNet

Convert DataTable to List

For converting datatable to list we will create a extension method which we can use easily anywhere in the project.

so, first of all add this class in your project


public static class DataReaderExtensions { #region "-- Public -- " #region "-- Methods --" /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="dr"></param> /// <returns></returns> public static List<T> MapToList<T>(this DbDataReader dr) where T : new() { List<T> RetVal = null; var Entity = typeof(T); var PropDict = new Dictionary<string, PropertyInfo>(); string Name = string.Empty; try { if (dr != null && dr.HasRows) { RetVal = new List<T>(); var Props = Entity.GetProperties(BindingFlags.Instance | BindingFlags.Public); PropDict = Props.ToDictionary(p => p.Name.ToUpper(), p => p); while (dr.Read()) { T newObject = new T(); for (int Index = 0; Index < dr.FieldCount; Index++) { Name = dr.GetName(Index).ToUpper(); if (PropDict.ContainsKey(dr.GetName(Index).ToUpper())) { var Info = PropDict[dr.GetName(Index).ToUpper()]; if ((Info != null) && Info.CanWrite) { var Val = dr.GetValue(Index); Info.SetValue(newObject, (Val == DBNull.Value) ? null : Val, null); } } } RetVal.Add(newObject); } } } catch (Exception) { throw; } return RetVal; } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="dr"></param> /// <returns></returns> public static List<T> DataTableToList<T>(this DataTable table) where T : class, new() { try { List<T> list = new List<T>(); foreach (var row in table.AsEnumerable()) { T obj = new T(); foreach (var prop in obj.GetType().GetProperties()) { try { PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name); if (propertyInfo.PropertyType.IsEnum) { propertyInfo.SetValue(obj, Enum.Parse(propertyInfo.PropertyType, row[prop.Name].ToString())); } else { Type t = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType; if (row.Table.Columns.Contains(prop.Name)) { if (propertyInfo.PropertyType == typeof(Int32)) { int value = 0; var isvalid = Int32.TryParse(Convert.ToString(row[prop.Name]), out value); if (isvalid) propertyInfo.SetValue(obj, value, null); } else if (propertyInfo.PropertyType == typeof(bool)) { var safevalue = string.IsNullOrEmpty(Convert.ToString(row[prop.Name])) ? false : Convert.ToBoolean(row[prop.Name]); propertyInfo.SetValue(obj, safevalue, null); } else if (propertyInfo.PropertyType == typeof(int?)) { int value = 0; var isvalid = Int32.TryParse(Convert.ToString(row[prop.Name]), out value); if (isvalid) propertyInfo.SetValue(obj, value, null); else propertyInfo.SetValue(obj, 0, null); } else if (propertyInfo.PropertyType == typeof(DateTime?)) { DateTime value; var isvalid = DateTime.TryParse(Convert.ToString(row[prop.Name]), out value); if (isvalid) propertyInfo.SetValue(obj, value, null); else propertyInfo.SetValue(obj, null, null); } else if (propertyInfo.PropertyType == typeof(DateTime)) { DateTime value; var isvalid = DateTime.TryParse(Convert.ToString(row[prop.Name]), out value); if (isvalid) propertyInfo.SetValue(obj, value, null); } else if (propertyInfo.PropertyType == typeof(Decimal)) { var safevalue = string.IsNullOrEmpty(Convert.ToString(row[prop.Name])) ? 0 : Convert.ToDecimal(row[prop.Name]); propertyInfo.SetValue(obj, safevalue, null); } else { propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null); } // propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null); } } } catch (Exception ex) { continue; } } list.Add(obj); } return list; } catch { return null; } } private static T GetItem<T>(DataRow dr) { Type temp = typeof(T); T obj = Activator.CreateInstance<T>(); foreach (DataColumn column in dr.Table.Columns) { foreach (PropertyInfo pro in temp.GetProperties()) { if (pro.Name == column.ColumnName) pro.SetValue(obj, dr[column.ColumnName], null); else continue; } } return obj; } } #endregion "-- Methods --" #endregion "-- Public -- "
    public static class TConverter
    {
        public static T ChangeType<T>(object value)
        {
            return (T)ChangeType(typeof(T), value);
        }
        public static object ChangeType(Type t, object value)
        {
            TypeConverter tc = TypeDescriptor.GetConverter(t);
            return tc.ConvertFrom(value);
        }

    }
After adding these two classes now we can use our extension method in controller, For using this we have to do this

   public class HomeController : Controller
    {
        public ActionResult Index()
        {
            DataTable table = DummyDataTableSource();
            var list= table.DataTableToList<Employee>();
            return View();
        }

         private static DataTable DummyDataTableSource()
        {
            DataTable table = new DataTable();
            table.Columns.Add("Name");
            table.Columns.Add("Number");
            table.Columns.Add("Address");
            table.Columns.Add("City");


            for (int i = 0; i < 10; i++)
            {
                DataRow dr = table.NewRow();
                dr["Name"] = "Name " + i;
                dr["Number"] = "Number " + i;
                dr["Address"] = "Address " + i;
                dr["City"] = "City " + i;
                table.Rows.Add(dr);
            }

            return table;
        }
    }

You have to add this class in the project which we will use while converting datatable to list .

public class Employee
    {
        public string Name { get; set; }
        public string Number { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
    }

For converting datatable to list we have to do this. This will convert datatable to list of type Employee.

DataTable table = DummyDataTableSource();
var list= table.DataTableToList<Employee>();

You can check the converted list in the image

How to Convert DataTable to List

This is how we can convert datatable to list in Asp.Net.

S
Shubham Batra
Programming author at Code2Night — sharing tutorials on ASP.NET, C#, and more.
View all posts →

Related Articles

Get random number in asp.net C#
Dec 23, 2023
Integrate Stripe Payment Gateway In ASP.NET Core 8.0
Nov 23, 2023
Integrate Stripe Payment Gateway In ASP.NET Core 7.0
Jul 22, 2023
Implement Stripe Payment Gateway In ASP.NET Core
Jul 01, 2023
Previous in C#
How to shuffle list in c#
Next in C#
The report definition is not valid or is not supported by this ve…
Buy me a pizza

Comments

On this page

🎯

Interview Prep

Ace your C# interview with curated Q&As for all levels.

View C# Interview Q&As

More in C#

  • Zoom C# Wrapper Integration 12905 views
  • Convert HTML String To Image In C# 11487 views
  • The report definition is not valid or is not supported by th… 10828 views
  • Replacing Accent Characters with Alphabet Characters in CSha… 9799 views
  • Get IP address using c# 8658 views
View all C# posts →

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1770
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • ASP.NET
  • Asp.net Core
  • ASP.NET Core, C#
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • HTML/CSS
  • Java
  • JavaScript
  • Node.js
  • Python
  • Python 3.11, Pandas, SQL
  • Python 3.11, SQL
  • Python 3.11, SQLAlchemy
  • Python 3.11, SQLAlchemy, SQL
  • Python 3.11, SQLite
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ·  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor