Introduction
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
- Assemblies
- Modules
- Types
Model Properties
Create simple variable in the model class. In there, you can use whatever data types you want.
- public class Logininfo
- {
- public int UserID { get; set; }
- public string UserName { get; set; }
- }
- Public Class LogininfoList
- {
- public List< Logininfo > ListLogininfo { get; set; }
- }
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.
- CREATE TABLE LoginInformation(
- UserID int null,
- UserName varchar null )
Conversion
If ADO.NET is used there, after the execution, data fills on dataset.
- SqlCommand command = new SqlCommand(sp, connection) { CommandType = CommandType.StoredProcedure, CommandTimeout = connection.ConnectionTimeout };
- connection.Open();
- command.Parameters.AddRange(prms);
- DataSet dataSet = new DataSet();
- (new SqlDataAdapter(command)).Fill(dataSet);
- command.Parameters.Clear();
- return dataSet;
Convert table into list using this extension. ToList<>
- LogininfoList obj= new LogininfoList();
- Obj. ListLogininfo= ds.Tables[1].ToList<Logininfo>().ToList();
Reflection has create instance of property & data transfer from table into list given below the code.
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Linq;
- using System.Reflection;
- public static IList<T> ToList<T>(this DataTable table) where T : new()
- {
- IList<PropertyInfo> properties = typeof(T).GetProperties().ToList();
- IList<T> result = new List<T>();
- foreach (var row in table.Rows)
- {
- var item = CreateItemFromRow<T>((DataRow)row, properties);
- result.Add(item);
- }
- return result;
- }
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.....

saravana kumarPosted Sep 20, 2018, 9:07 AM
What is CreateItemFromRow here?
Pradeep YadavPosted Jun 11, 2017, 1:18 PM
Nice. Thanks for share!!!