C# – All rows of specific column in dataset

cdatarowdatasetvb.net

I have a DataSet that looks like this :

| A | B | C | D | E | F | G | H | I | ... |   Z  |
--------------------------------------------------
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | ... |  26  |
|11 |22 |33 |44 |55 |66 |77 |88 |99 | ... | 2626 |
|111|222|333|444|555|666|777|888|999| ... |262626|

Values not related. I just have a lot of columns.

I would like to go through all rows for a specific column.
Is it possible without going though all columns ? Because right now the only thing I can think of is this (let's say I want all rows for column D)

C#

foreach(DataRow row in myDataSet.Tables(0).Rows)
   if(row.Column == myDataSet.Tables(0).Columns("D"))
      MessageBox.Show("I'm in Column B");

VB

For Each row As DataRow In myDataSet.Tables(0).Rows
If row.Column Is myDataSet.Tables(0).Columns("D") Then
MessageBox.Show("I'm in Column B")
End If
Next

But this would loop through all columns. I would like to use a collection like
myDataSet.Tables(0).Columns("D").Rows but it does not exist.

Best Answer

DataRow has an indexer that you can use:

foreach(DataRow row in myDataSet.Tables[0].Rows)
    Console.WriteLine("I'm in Column B: " + row["D"]);

You can access it via name or ordinal-index of the field. The third overload can be used if you have a reference of DataColumn and is used by the others after the column was found. If you don't want to "search" for the column(although the effort is negligible) use this:

DataColumn col = myDataSet.Tables[0].Columns["D"];
foreach(DataRow row in myDataSet.Tables[0].Rows)
        Console.WriteLine("I'm in Column B: " + row[col]);

But you could also use Linq, for example if you want to sum all values in this column:

int dTotal = myDataSet.Tables[0].AsEnumerable().Sum(r => r.Field<int>("D"));
Related Topic