C#

How to iterate through a DataTable

27 September 2026 · 6 min read

How to iterate through a DataTable

Navigating and manipulating data within applications is a fundamental task for any developer. When working with .NET applications, the DataTable object often serves as a robust in-memory representation of tabular data. Understanding how to iterate through a DataTable effectively is not just about writing functional code; it’s about ensuring performance, maintainability, and data integrity. This guide delves into various methods for traversing DataTables, from traditional loops to modern LINQ expressions, equipping you with the knowledge to choose the best approach for your specific needs.

Whether you’re populating UI elements, performing complex calculations, or transforming data for storage, the ability to efficiently access each DataRow and DataColumn is paramount. We’ll explore the nuances of each iteration technique, highlighting their strengths and weaknesses, and provide practical examples to solidify your understanding. As an experienced developer, I’ve seen firsthand how an optimized iteration strategy can significantly impact application responsiveness and resource utilization.

Understanding the DataTable Structure in .NET

Before diving into iteration techniques, it’s essential to grasp the fundamental structure of a DataTable. A DataTable represents a single table in memory, much like a table in a relational database. It is part of the System.Data namespace and is a core component of the ADO.NET architecture. Each DataTable consists of a collection of DataRow objects and a collection of DataColumn objects.

Each DataRow within the DataTable represents a single record, and each DataColumn defines the schema for a particular field, including its name, data type, and other properties like whether it allows null values or is a primary key. When you fetch data from a database using a DataAdapter, it typically populates a DataTable within a DataSet. This structured approach makes DataTables incredibly versatile for temporary data storage, offline data manipulation, and data binding.

Efficient data manipulation often hinges on how well you can access and process individual cells. For instance, if you have a DataTable containing sales figures, you might need to sum up all sales for a particular product, update prices based on a discount percentage, or filter records that meet certain criteria. Each of these operations requires a systematic way to iterate through the table’s rows and columns. Properly understanding this structure is the first step towards writing robust and efficient data processing logic.

Traditional Iteration Methods: For and ForEach Loops

The most straightforward and commonly used methods to iterate through a DataTable involve traditional C looping constructs: the for loop and the foreach loop. These methods are fundamental and provide explicit control over the iteration process, making them suitable for a wide range of scenarios, especially when working with older .NET frameworks or when fine-grained control is necessary.

The foreach loop is often preferred for its simplicity and readability when you need to process every row in the table. It iterates directly over the Rows collection of the DataTable, providing access to each DataRow object in sequence. This method is generally recommended when you don’t need to know the index of the current row or when you don’t intend to modify the collection’s structure during iteration.

// Example using foreach loop DataTable myDataTable = GetMyDataTable(); // Assume this method returns a populated DataTable foreach (DataRow row in myDataTable.Rows) { // Access data by column name or index string customerName = row["CustomerName"].ToString(); int orderID = (int)row["OrderID"]; Console.WriteLine($"Customer: {customerName}, Order ID: {orderID}"); // You can also iterate through columns within each row foreach (DataColumn col in myDataTable.Columns) { Console.WriteLine($" Column: {col.ColumnName}, Value: {row[col]}"); } } 

On the other hand, the for loop provides an index-based iteration, which is crucial when you need to access rows by their numerical position, perform operations that depend on the row’s index, or iterate backward. It’s also necessary when you might need to remove rows from the DataTable during iteration, as modifying the collection while using a foreach loop can lead to runtime errors. For such scenarios, iterating backward with a for loop is a common pattern to avoid index shifting issues.

// Example using for loop for (int i = 0; i < myDataTable.Rows.Count; i++) { DataRow row = myDataTable.Rows[i]; string productName = row["ProductName"].ToString(); decimal price = (decimal)row["Price"]; Console.WriteLine($"Product: {productName}, Price: {price:C}"); // If removing rows, iterate backward: // for (int i = myDataTable.Rows.Count - 1; i >= 0; i--) // { // DataRow currentRow = myDataTable.Rows[i]; // if (someCondition) // { // currentRow.Delete(); // Mark row for deletion // } // } // myDataTable.AcceptChanges(); // Commit deletions } 

Both for and foreach loops are robust for iterating through DataTables. The choice between them often comes down to whether you need the row index or plan to modify the collection during iteration. For simple read-only traversal, foreach generally offers better readability.

Modern Approaches: LINQ to DataSet ----------------------------------

For developers working with .NET Framework 3.5 or later, Language Integrated Query (LINQ) offers a powerful, expressive, and often more efficient way to query and iterate through a DataTable. LINQ to DataSet extends LINQ capabilities to objects that implement IDataReader, specifically targeting DataSet and DataTable objects. This approach allows you to write queries against your DataTable using a syntax similar to SQL, making data manipulation significantly more intuitive and concise.

The primary method to enable LINQ queries on a DataTable is by using the AsEnumerable() extension method. This method returns an enumerable collection of DataRow objects, allowing you to apply standard LINQ operators like Where, Select, OrderBy, and GroupBy. This not only simplifies complex data filtering and projection but also enhances code readability and reduces the amount of boilerplate code compared to traditional loops.

Featured Snippet Optimized Paragraph: For optimal efficiency and readability when you need to filter, sort, or project data from a DataTable, especially in modern .NET applications, using LINQ to DataSet via the AsEnumerable() method is generally the most recommended approach. It leverages the power of Language Integrated Query to provide a fluent, SQL-like syntax for data manipulation, which can significantly reduce code complexity and improve performance for complex data operations compared to manual for or foreach loops. This method is particularly beneficial for scenarios involving multiple filtering criteria or data transformations.

Here’s how you can use LINQ to DataSet to filter and project data:

// Example using LINQ to DataSet DataTable myDataTable = GetMyDataTable(); // Assume populated DataTable // Filter rows where "Category" is "Electronics" and select "ProductName" and "Price" var electronicsProducts = myDataTable.AsEnumerable() .Where(row => row.Field<string>("Category") == "Electronics") .Select(row => new { ProductName = row.Field<string>("ProductName"), Price = row.Field<decimal>("Price") }); Console.WriteLine("Electronics Products:"); foreach (var product in electronicsProducts) { Console.WriteLine($" {product.ProductName} - {product.Price:C}"); } 

LINQ to DataSet is not just for filtering; it’s incredibly powerful for aggregation, joining multiple DataTables, and creating new DataTables from existing ones. According to a [How can I achieve the same thing using DataTable?

DataTable dt = new DataTable(); SqlDataAdapter adapter = new SqlDataAdapter(cmd); adapter.Fill(dt); foreach(DataRow row in dt.Rows) { TextBox1.Text = row["ImagePath"].ToString(); } 

…assumes the connection is open and the command is set up properly. I also didn’t check the syntax, but it should give you the idea.](<https://www.infoq.com/news/2007/11/lin Question & Answer :

I need to iterate through a DataTable. I have a column there named ImagePath.

When I am using DataReader I do it this way:

SqlDataReader dr = null; dr = cmd.ExecuteReader(); while (dr.Read()) { TextBox1.Text = dr[>)