How to Convert DataTable into List in C# ?
In this article, we are going to convert DataTable into a List in C#. There are three ways to do it. We will see in following simple program how to do it. The program is self-explanatory in the form of code comments.
Code Snippet:-
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace BlogsProgram
{
public class Program
{
// Creating an Entity class for Employee
public class Employee
{
public int EmpID { get; set; }
public string EmpName { get; set; }
public string City { get; set; }
}
public static void Main(string[] args)
{
Code Snippet:-
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace BlogsProgram
{
public class Program
{
// Creating an Entity class for Employee
public class Employee
{
public int EmpID { get; set; }
public string EmpName { get; set; }
public string City { get; set; }
}
public static void Main(string[] args)
{
// Creating Object of Program class to access its Members
Program _obj_Program = new Program();
// Defined Tabble as "Employee".
DataTable dt = new DataTable("Employee");
// Defined "EmpID" column as Integer Datatype.
dt.Columns.Add("EmpID", typeof(Int32));
// Defined "EmpName" column as String Datatype.
dt.Columns.Add("EmpName", typeof(string));
// Defined "EmpRank" column as String Datatype.
dt.Columns.Add("Rank", typeof(string));
//Inserting Data into above-defined DataTable
dt.Rows.Add(1, "Raj", "Hyderabad"); // Adding Row 1 to Table
dt.Rows.Add(2, "Shubh", "Nagpur"); // Adding Row 2 to Table
dt.Rows.Add(3, "Neha", "Pune"); // Adding Row 3 to Table
//Approach 1:- Calling Emplist() method with the Datatable Parameter to Convert it into List using Loop
Program _obj_Program = new Program();
// Defined Tabble as "Employee".
DataTable dt = new DataTable("Employee");
// Defined "EmpID" column as Integer Datatype.
dt.Columns.Add("EmpID", typeof(Int32));
// Defined "EmpName" column as String Datatype.
dt.Columns.Add("EmpName", typeof(string));
// Defined "EmpRank" column as String Datatype.
dt.Columns.Add("Rank", typeof(string));
//Inserting Data into above-defined DataTable
dt.Rows.Add(1, "Raj", "Hyderabad"); // Adding Row 1 to Table
dt.Rows.Add(2, "Shubh", "Nagpur"); // Adding Row 2 to Table
dt.Rows.Add(3, "Neha", "Pune"); // Adding Row 3 to Table
//Approach 1:- Calling Emplist() method with the Datatable Parameter to Convert it into List using Loop
_obj_Program.EmpList(dt);
//Approach 2:- Calling EmployeeListUsingLinq() method with Datatable Parameter to Convert it into List using Linq
_obj_Program.EmployeeListUsingLinq(dt);
//Approach 3:- Calling EmployeeListUsingLinq() method with Datatable Parameter to Convert it into List using Linq
List<Employee> EmployeeList = new List<Employee>();
EmployeeList = _obj_Program.ConvertDataTable<Employee>(dt);
}
/// <summary>
/// Method to Convert Datatable into List using Loop
/// </summary>
/// <param name="dt"></param>
public void EmpList(DataTable dt)
{
/* Creating Employee List to save Data From Datatable after Conversion.*/
List<Employee> EmployeeList = new List<Employee>();
//Looping Through Data Table
for (int i = 0; i < dt.Rows.Count; i++)
{
Employee _obj_Employee = new Employee();
_obj_Employee.EmpID = Convert.ToInt32(dt.Rows[i]["EmpID"]);
_obj_Employee.EmpName = dt.Rows[i]["EmpName"].ToString();
_obj_Employee.City = dt.Rows[i]["City"].ToString();
/* Adding Employee Object to Employee List after each iteration.*/
EmployeeList.Add(_obj_Employee);
}
}
/// <summary>
/// Methos to Convert Datatable using Linq
/// </summary>
/// <param name="dt"></param>
public void EmployeeListUsingLinq(DataTable dt)
{
//Approach 2:- Calling EmployeeListUsingLinq() method with Datatable Parameter to Convert it into List using Linq
_obj_Program.EmployeeListUsingLinq(dt);
//Approach 3:- Calling EmployeeListUsingLinq() method with Datatable Parameter to Convert it into List using Linq
List<Employee> EmployeeList = new List<Employee>();
EmployeeList = _obj_Program.ConvertDataTable<Employee>(dt);
}
/// <summary>
/// Method to Convert Datatable into List using Loop
/// </summary>
/// <param name="dt"></param>
public void EmpList(DataTable dt)
{
/* Creating Employee List to save Data From Datatable after Conversion.*/
List<Employee> EmployeeList = new List<Employee>();
//Looping Through Data Table
for (int i = 0; i < dt.Rows.Count; i++)
{
Employee _obj_Employee = new Employee();
_obj_Employee.EmpID = Convert.ToInt32(dt.Rows[i]["EmpID"]);
_obj_Employee.EmpName = dt.Rows[i]["EmpName"].ToString();
_obj_Employee.City = dt.Rows[i]["City"].ToString();
/* Adding Employee Object to Employee List after each iteration.*/
EmployeeList.Add(_obj_Employee);
}
}
/// <summary>
/// Methos to Convert Datatable using Linq
/// </summary>
/// <param name="dt"></param>
public void EmployeeListUsingLinq(DataTable dt)
{
/* Creating Employee List to save Data From Datatable after Conversion.*/
List<Employee> EmployeeList = new List<Employee>();
EmployeeList = (from DataRow dr in dt.Rows
select new Employee()
{
EmpID = Convert.ToInt32(dr["EmplID"]),
EmpName = dr["EmpName"].ToString(),
City = dr["City"].ToString()
}).ToList();
}
/// <summary>
/// Generic method to convert Datatable into List
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <returns></returns>
private List<T> ConvertDataTable<T>(DataTable dt)
{
List<T> data = new List<T>();
foreach (DataRow row in dt.Rows)
{
// calling GetItem() to convert datatable row into an object.
T item = GetItem<T>(row);
// Adding object into List Object
data.Add(item);
}
// returning list object
return data;
}
// Getting Datarow as input param.
private static T GetItem<T>(DataRow dr)
{
Type temp = typeof(T);
T obj = Activator.CreateInstance<T>();
//Looping through Datarow and Unwrapping DataColumn and putting them in Object as property
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;
}
}
//Returning converted data row as object with column as its properties.
return obj;
}
}
}
List<Employee> EmployeeList = new List<Employee>();
EmployeeList = (from DataRow dr in dt.Rows
select new Employee()
{
EmpID = Convert.ToInt32(dr["EmplID"]),
EmpName = dr["EmpName"].ToString(),
City = dr["City"].ToString()
}).ToList();
}
/// <summary>
/// Generic method to convert Datatable into List
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <returns></returns>
private List<T> ConvertDataTable<T>(DataTable dt)
{
List<T> data = new List<T>();
foreach (DataRow row in dt.Rows)
{
// calling GetItem() to convert datatable row into an object.
T item = GetItem<T>(row);
// Adding object into List Object
data.Add(item);
}
// returning list object
return data;
}
// Getting Datarow as input param.
private static T GetItem<T>(DataRow dr)
{
Type temp = typeof(T);
T obj = Activator.CreateInstance<T>();
//Looping through Datarow and Unwrapping DataColumn and putting them in Object as property
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;
}
}
//Returning converted data row as object with column as its properties.
return obj;
}
}
}
Comments
Post a Comment