Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# DataTable, get value by Row/Column index [duplicate]

I have a DataTable which is populated by a csv file, with 8 columns and approximately 2000 rows. I wish to populate an object with my csv values that are currently stored in my DataTable

How do I index a specific DataTable cell? In other words, I wish to treat the data table in a similar way you would a 2D array, like so:

string value = array[i][j];

Here is my code:

DataTable d = GetDataTableFromCSVFile(file);
for (int i = 0; i < d.Rows.Count; i++)
{
    for (int j = 0; j < d.Columns.Count; j++)
    {
         //string x = d[i][j]; <-- something like this.
    }
} 
like image 399
Barney Chambers Avatar asked Aug 01 '17 02:08

Barney Chambers


2 Answers

like this

string x = d.Rows[i][j].ToString()
like image 154
nan lin Avatar answered Sep 22 '22 12:09

nan lin


The best way to iterate the DataTable. Foreach works faster then for loop:

foreach (DataRow dtRow in dtTable.Rows)
{
    foreach(DataColumn dc in dtTable.Columns)
    {
      var field1 = dtRow[dc].ToString();
    }
}
like image 40
Sanjay Avatar answered Sep 21 '22 12:09

Sanjay