You don't need to surround your for
loop with a foreach
loop on the Rows. (You are not using the dr
at all)
for (int idx = 0; idx < dt.Rows.Count; idx++)
{
Console.WriteLine(dt.Columns[0].ColumnName + " ");
Console.WriteLine(dt.Rows[idx].ItemArray[0] + " ");
Console.WriteLine(dt.Columns[1].ColumnName + " ");
Console.WriteLine(dt.Rows[idx].ItemArray[1] + " ");
Console.WriteLine(dt.Columns[4].ColumnName + " ");
Console.WriteLine(dt.Rows[idx].ItemArray[4] + " ");
}
A bit more generic version:
int[] columnIndexes = new[] { 0, 1, 4 };
for (int rowIndex = 0; rowIndex < dt.Rows.Count; rowIndex++)
{
for (int columnIndex = 0; columnIndex < columnIndexes.Length; columnIndex++)
{
Console.WriteLine(dt.Columns[columnIndex].ColumnName + " ");
Console.WriteLine(dt.Rows[rowIndex].ItemArray[columnIndex] + " ");
}
}
If you want to iterate through the Rows collection with foreach then you can do but it is a bit more trickier.
DataTable's Rows property is a DataRowCollection. It exposes a GetEnumerator
method, which is essential for the foreach
loop.
foreach (DataRow dr in dt.Rows)
{
//dr does not provide you direct access to the ColumnName
}
You can't access the ColumnName from the DataRow directly. All need to do is to create a "lookup table" for the column names where the key is the index and the value is the name of the column.
int colIdx = 0;
var columnNames = dt.Columns
.Cast<DataColumn>()
.ToDictionary(_ => colIdx++, column => column.ColumnName);
After that your foreach loop would look like this:
int[] columnIndexes = new[] {0, 1, 4};
foreach (DataRow row in dt.Rows)
{
for (int columnIndex = 0; columnIndex < columnIndexes.Length; columnIndex++)
{
Console.WriteLine(columnNames[columnIndex] + " ");
Console.WriteLine(row.ItemArray[columnIndex] + " ");
}
}
foreach
or thefor
loop. You don't need both.foreach (var dr in dt.Rows) Console.WriteLine($"{dr[0]} - {dr[1]} - {dr[4]}");