In this blog, learn how to convert table data into list data using Reflection and LINQ. You can use the data passing from the server side to the 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, and types.

Model Properties

Create a simple variable in the model class in which you can use whatever data types that you want to.

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 note that you must set the column name as the model properties. If there is a mismatch, then the name reflection will not work.

CREATE TABLE logininformation
  (
     userid   INT NULL,
     username VARCHAR NULL
  )

Conversion

If ADO.NET is used in this situation, then after the execution, the data will fill the 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 the table into a list by using the extension ToList<> .

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

Reflection has created an instance of a property and data transfer from the table to the list that is provided below in 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 when it comes to using ADO.NET.

Conclusion

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

Advertisements