How to Convert a DataTable to a List of Objects in C#
By FoxLearn 2/27/2025 4:21:32 AM 49
Step 1. Define the Conversion Method
The generic method will accept a DataTable
and convert it into a List<T>
, where T
represents any object type.
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Data; public static class DataTableExtensions { public static List<T> ToListOfObjects<T>(this DataTable dataTable) where T : new() { List<T> resultList = new List<T>(); try { // Serialize DataTable to JSON and then Deserialize to List<T> var json = JsonConvert.SerializeObject(dataTable, Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); resultList = JsonConvert.DeserializeObject<List<T>>(json); } catch (Exception ex) { // Handle errors Console.WriteLine("Error during DataTable to List conversion: " + ex.Message); } return resultList; } }
The conversion method will allow you to convert any DataTable
into a List<T>
, where T
can be any object type.
In this example:
Serialization and Deserialization:
- We first serialize the
DataTable
into JSON format. - Then, we deserialize the JSON into a
List<T>
, whereT
is the object type we wish to use.
- We first serialize the
Error Handling:
- The conversion process is wrapped in a
try-catch
block to ensure we handle any issues that might arise during the serialization or deserialization process. If an error occurs, it logs the exception and returns an empty list.
- The conversion process is wrapped in a
Return Value:
- The method returns a
List<T>
containing objects of typeT
, each representing a row in the originalDataTable
.
- The method returns a
Step 2. Using the Conversion Method
For example, let's assume we have a Product
class, and we want to convert our DataTable
to a list of Product
objects.
public class Product { public int ProductId { get; set; } public string ProductName { get; set; } public decimal Price { get; set; } } public List<Product> GetProducts() { string sql = "SELECT * FROM Products"; // Your SQL query DataTable dataTable = GetDataTable(sql); // Assume GetDataTable() gets a DataTable from your database // Convert DataTable to List<Product> List<Product> products = dataTable.ToListOfObjects<Product>(); return products; } public DataTable GetDataTable(string sqlQuery) { // Example code to retrieve DataTable from a database (ADO.NET) DataTable dataTable = new DataTable(); using (SqlConnection connection = new SqlConnection("YourConnectionString")) { SqlDataAdapter adapter = new SqlDataAdapter(sqlQuery, connection); adapter.Fill(dataTable); } return dataTable; }
Practical Considerations
Null Handling:
- The
NullValueHandling.Ignore
setting inJsonConvert.SerializeObject
ensures that null values in theDataTable
are ignored, resulting in cleaner conversion.
- The
Performance:
- While JSON serialization is a convenient method, it can be slower for very large
DataTable
objects. In such cases, consider using alternative mapping techniques that might provide better performance.
- While JSON serialization is a convenient method, it can be slower for very large
Schema Matching:
- Ensure that the column names in the
DataTable
match the property names in the target object class (T
). If they don’t match, the JSON conversion might fail or produce incorrect results.
- Ensure that the column names in the
This method provides a straightforward and flexible way to convert a DataTable
into a list of objects in C#. It’s particularly useful for developers working with ADO.NET or those who frequently need to map data from a database into custom classes.