Convert Datatable To List In C#

Introduction:

When dealing with information in C#, it is frequently necessary to employ a DataTable instance to store the data. A DataTable serves as a robust data container enabling various data manipulation and analysis operations. Nevertheless, there are instances where transforming a DataTable into a collection of objects becomes essential for subsequent operations. In this guide, we will explore extensively the process of converting a DataTable into a list in C#.

What is a DataTable?

A DataTable within C# is a type that serves the purpose of depicting a dataset in the computer's memory. It mirrors the structure of a typical table found in a database, consisting of rows and columns. Data can be imported into a DataTable from different origins like databases, XML files, or CSV files. Following the loading of information into a DataTable, users can carry out operations like manipulation, sorting, filtering, and presenting data in diverse formats.

What is a List?

A List represents a grouping of elements sharing a common data type. It serves as a resizable Array offering flexibility. Lists offer a range of features including insertion, deletion, sorting, filtering, and item retrieval.

Why convert a DataTable to a List?

While a DataTable is a robust data structure, there are situations where it may not be the most optimal format for subsequent operations. For instance, if you aim to execute LINQ queries on the data or utilize an external library that necessitates an object list, converting the DataTable to a list could enhance efficiency. Furthermore, working with a list might be more convenient when dealing with a smaller data subset or when requiring specialized data manipulation.

Steps to Convert DataTable to List in C#

The following are the steps to convert a DataTable to a list in C#:

  • Create a class that represents the data in each row of the DataTable. This class should have attributes that correspond to the columns in the DataTable.
  • Create a new List object that will hold the converted data.
  • Loop through each row in the DataTable.
  • Create a new object of the class created in step 1.
  • Populate the properties of the object with the values from the current row in the DataTable.
  • Add the object to the List created in step 2.
  • Return the List.

Let's consider an example to grasp the process of converting a DataTable to a List in C#.

Convert the given DataTable called " Employee " containing columns such as " Id ", " Name ", and " Salary " into a List of objects representing " Employee " instances.

C# Code:

Example

DataTable dt = new DataTable();
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Salary", typeof(int));
dt.Rows.Add(1, "John", 5000);
dt.Rows.Add(2, "Mary", 6000);
dt.Rows.Add(3, "Jane", 7000);

To transform this DataTable into a collection of Employee instances, we will generate a class called " Employee " containing attributes such as " Id ", " Name ", and " Salary ".

C# Code:

Example

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Salary { get; set; }
}

Next, we'll loop through the rows of the DataTable and instantiate a fresh Employee object for every row. Subsequently, we append this object to the List.

C# Code:

Example

List<Employee> employees = new List<Employee>();
foreach (DataRow row in dt.Rows)
{
    Employee employee = new Employee();
    employee.Id = Convert.ToInt32(row["Id"]);
    employee.Name = row["Name"].ToString();
    employee.Salary = Convert.ToInt32(row["Salary"]);
    employees.Add(employee);
}

In the preceding code snippet, we initialized a new List instance to store Employee objects, labeled as " employees ". Subsequently, a foreach loop was employed to sequentially process each row within the DataTable named " dt ". During each iteration, a fresh Employee object dubbed as " employee " was instantiated. The respective values from the " Id ", " Name ", and " Salary " columns of the current row were then mapped to the corresponding properties of the Employee object. Ultimately, this instantiated object was appended to the " employees " List.

We are now able to utilize this List for data manipulation or to exhibit it in an alternative layout.

Conclusion:

Converting a DataTable to a List can be advantageous in different situations where there is a need to modify the data or showcase it in an alternative layout. The process includes cycling through the rows of the DataTable and generating a fresh object for each row to encapsulate the data. Subsequently, this object is appended to the List. This guide covers the procedure of converting a DataTable into a List in C# with the help of an illustration.

Input Required

This code uses input(). Please provide values below: