C#中DataTable新增遍历,可以使用foreach循环或者for循环进行遍历。示例代码如下:
// 创建DataTable
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Age", typeof(int));
dt.Rows.Add(1, "Tom", 20);
dt.Rows.Add(2, "Jack", 25);
dt.Rows.Add(3, "Mary", 22);
// 使用foreach循环遍历DataTable
foreach (DataRow row in dt.Rows)
{
Console.WriteLine("ID: {0}, Name: {1}, Age: {2}", row["ID"], row["Name"], row["Age"]);
}
// 使用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"]);
}
其中,使用foreach循环遍历DataTable时,每次循环都会将DataTable中的一行数据转换为DataRow对象,方便获取行数据中的具体字段值。使用for循环遍历DataTable时,则需要使用DataRowCollection集合的索引获取每一行数据。