Convert Table Data To List Using Reflection

Introduction

In this blog, learn how to convert table data into list data using Reflection & LINQ. Notably, you can use the data passing from Server side to client side.

Reflection

You can use Reflection to dynamically create an instance of a type, bind the type to an existing object or get the type from existing object, and invoke its methods or access fields and properties. If you are using attributes in your code, Reflection enables you to access them

It will provide object

  • Assemblies
  • Modules
  • Types 

Model Properties

Create simple variable in the model class. In there, you can use whatever data types you want.

  1. public class Logininfo  
  2.     {  
  3.         public int UserID { getset; }  
  4.         public string UserName { getset; }  
  5.           
  6.     }  
  7. Public Class LogininfoList  
  8. {  
  9. public List< Logininfo > ListLogininfo { getset; }    
  10. }  

Table Column

Create a table, but must set the column name as model properties. If there is any mismatch, the name reflection wouldn’t work.

  1. CREATE TABLE LoginInformation(  
  2.         UserID int null,  
  3.         UserName varchar null )  

Conversion

If  ADO.NET is used there, after the execution, data fills on dataset.

  1. SqlCommand command = new SqlCommand(sp, connection) { CommandType = CommandType.StoredProcedure, CommandTimeout = connection.ConnectionTimeout };  
  2.                 connection.Open();  
  3. command.Parameters.AddRange(prms);  
  4.   DataSet dataSet = new DataSet();  
  5.                 (new SqlDataAdapter(command)).Fill(dataSet);  
  6.                 command.Parameters.Clear();  
  7. return dataSet;  

Convert table into list using this extension. ToList<>

  1. LogininfoList obj= new LogininfoList();  
  2. Obj. ListLogininfo= ds.Tables[1].ToList<Logininfo>().ToList();  

Reflection has create instance of property & data transfer from table into list given below the code.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data;  
  4. using System.Linq;  
  5. using System.Reflection;  
  6.   public static IList<T> ToList<T>(this DataTable table) where T : new()  
  7.         {  
  8.             IList<PropertyInfo> properties = typeof(T).GetProperties().ToList();  
  9.             IList<T> result = new List<T>();  
  10.   
  11.             foreach (var row in table.Rows)  
  12.             {  
  13.                 var item = CreateItemFromRow<T>((DataRow)row, properties);  
  14.                 result.Add(item);  
  15.             }  
  16.   
  17.             return result;  
  18.         }  

Note

This scenario is useful for using ADO.NET.

Conclusion

In this blog, we have table data converted to list using Reflection. If you have any queries, please tell me through the comments section.

Happy Coding.....