Code2night
  • Home
  • Blogs
  • Tutorial
  • Post Blog
  • Tools
    • Json Beautifier
    • Html Beautifier
  • Members
    • Register
    • Login
  1. Home
  2. Blogpost
12 Jun
2022

How to Convert DataTable to List

by Shubham Batra

89

Download Attachments

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

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

  • |
  • C# , AspNet , DataTable to List , Extension Methods

Comments

Tags

How to set Date and time format in IIS Manager
IIS Manager
IIS
Internet Information Services (IIS) Manager
Internet Information Services (IIS)
Internet Information Services
Error Handling In AspNet Core
Exception Handling Asp Net Core
Exception Handling
Exception Handling Asp Net
Aspnet
Creating Log Files in MVC
Error Handling in MVC
Exception Handling in AspNet
Handling Exceptions and Creating Error Logs in Asp net Mvc using base controller
net
Code2Tonight
Stopping Browser Reload On Save
Repository Pattern with ADONet in MVC
Repository Pattern With ASPNET MVC And AdoNet
MVC Crud Operation
Jquery Full Calender Integrated With ASPNET
Full Calendar
Jquery Calendar
Slick Slider
Slick Slider Example
responsive carousels
Entity Framework
MVC
Intergrate SummerNote Text Editor into AspNet MVC
Web Config
Auto Redirection
Redirection from Http to https
AspNet
Url Rewriting
Implement Stripe Payment Gateway In ASPNET Core
Stripe Payment Gateway
C#
AspNet Core
StripeNet
Postgre
PgAdmin4
PostgreSql
A Non Fatal Error Occured During Cluster Initialisation In Postgre SQL
Microsoft Outlook
Outlook Appointments
Microsoft Exchange Service
Send Email With HTML Template And PDF Using ASPNet C#
Send Email
Email with html template
email with pdf attachment
email with html and pdf
Microsoft Outlook Contacts
Outlook
Microsoft Exhchange Service
JSON
Convert string with dot notation to JSON
HTTP Error 5025 ANCM Out Of Process Startup Failure
Internet Information Service
Net core
Payumoney Integration With AspNet MVC
Prism js
Highlighting Syntax
Syntax Highlighting
code stylings
c#
Jquery AJax
Ajax
Jquery
Implement Stripe Payment Gateway In ASPNET
Using Checkout in an ASPNET Web Forms application
Stripe Payment
Stripe Payment Integration
Stripe Integeration
How to upload Image file using AJAX andjQuery
upload Image file using AJAX and jquery
Ajax call
file upload using ajax
file uploading using ajax and jquery
ConfigurationBuilder does not contain a definition for SetBasePath
Reading app json file in dot net core
Appsetting jso
Dot Net Core
Globalization and localization in ASPNET Core
Asp Net Core with Resource file resx
How to get the resx file strings in asp net core
Culture in Net core
Localisation in AspNet Core
Url Encryption in AspNet MVC
Url Encryption in C#
Url Encryption
Custom Helpers
Slick Slider with single slide
Slick
Vue js
Child Components
How to reload vue js child components
Net Core
Visual Studio
Net core 31
Razor
Zoom sdk
Zoom c# wrapper Inegration
zoom Integration in c#
Zoom Integration
Zoom window sdk
vue js toggle button
vue js
toggle buttons
vuejs
vue js toggle switch
SignalR
VueJs
SignalR in Net Core
Chat App in Vue js
Chat App using SignalR
AspNet Chat app
JPlayer
Html5 Audio Video Player
Music Player
QR Code Generator
QR Code
Jquery QR Code
AspNet MVC
Google Maps
Google map api
Places API
Google map Places API in AspNet
Jquery Autocomplete
Autocomplete
Jquery UI Autocomplete
ExcelDataReader
Import data from excel in AspNet
Card Number Formatting
Amex Card Format
Card Format
FCM
Cloud Messaging
Android Notifications
FCM Notifications for IOS
IOS Notifications
Angular js
apply css on child components in Angular js
Angular Mentions
Google Sign In
Google Login
Google Oauth Api
Social Login
Aspnet Mvc
Google + Api
Create and publish a package using Visual Studio (NET Framework
Windows)
Create and publish a nuget package
create your own nuget package
Image compress
Image optimization
compress Image
optimize Image
WebForm
AspNet Web Pages
Batch Script
Database backup
Powershell
ASpNet
Sql Server Backup
AspNet core 31
Aspnet core 21
HttpCookies in AspNet Core
LinkedIn Authentication
Login using LinkedIN
Social Login in AspNet
LinkedIn Authentication in AspNet MVC
LinkedIn Login in aspnet MVC
Shuffle List in c#
C#Net
Google Login in AspNet MVC
GoogleAuthentication Nuget package
Password Encryption
RFC Encryption
Encryption and Decryption
Encryption in AspNet
Base 64 Encryption
Base 64 Decryption
Swagger UI
Swashbuckle
SwashbuckleAspNetCore
Rest API
Postman
Api Testing
SSRS
SSRS Report
ASPNET MVC
ASPNET MVC SSRS Report
ssrs report
XlWorkbook
ClosedXml
Excel Export
Blazor
Syncfusion
SFGrid
Syncfusion SFgrid
Net
Net core 60
DataTable to List
Extension Methods
Microsoft Access Database Engine
Ace Ole Db 120
MicrosoftACEOLEDB120
OLE DB
Aspnet MVC
Ace OLE DB

Welcome To Code2night, A common place for sharing your programming knowledge,Blogs and Videos

  • Kurukshetra
  • [email protected]

Links

  • Home
  • Blogs
  • Tutorial
  • Post Blog

Popular Tags

Copyright © 2022 by Code2night. All Rights Reserved

  • Home
  • Blog
  • Login
  • SignUp
  • Contact
  • Json Beautifier