遍历datatable
时间: 2023-08-31 18:10:50 浏览: 106
可以使用foreach循环或者for循环进行遍历DataTable。使用foreach循环遍历DataTable时,每次循环都会将DataTable中的一行数据转换为DataRow对象,方便获取行数据中的具体字段值。示例代码如下:
```csharp
// 使用foreach循环遍历DataTable
foreach (DataRow row in dt.Rows)
{
Console.WriteLine("ID: {0}, Name: {1}, Age: {2}", row["ID"], row["Name"], row["Age"]);
}
```
使用for循环遍历DataTable时,需要使用DataRowCollection集合的索引获取每一行数据。示例代码如下:
```csharp
// 使用for循环遍历DataTable
for (int i = 0; i < dt.Rows.Count; i++)
{
Console.WriteLine("ID: {0}, Name: {1}, Age: {2}", dt.Rows[i]["ID"], dt.Rows[i]["Name"], dt.Rows[i]["Age"]);
}
```
<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* [C#中DataTable新增遍历](https://blog.csdn.net/qq_41177135/article/details/130828066)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *3* [asp.net DataTable导出Excel自定义列名的方法](https://download.csdn.net/download/weixin_38631225/12986745)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文