2

我有一个看起来像这样的数据集:

| 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|

不相关。我只是有很多列。

我想浏览特定列的所有行
是否有可能不经过所有列?因为现在我唯一能想到的就是这个(假设我想要 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

但这将遍历所有列。我想使用一个类似
myDataSet.Tables(0).Columns("D").Rows但它不存在的集合。

4

2 回答 2

5

DataRow有一个可以使用的索引器:

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

您可以通过字段的名称序数索引访问它。如果您有参考并且在找到该列后被其他人使用,则可以使用 第三个重载。DataColumn如果您不想“搜索”该列(尽管努力可以忽略不计),请使用:

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

但您也可以使用 Linq,例如,如果您想对这一列中的所有值求和:

int dTotal = myDataSet.Tables[0].AsEnumerable().Sum(r => r.Field<int>("D"));
于 2013-05-06T14:13:10.390 回答
2

In an immaginary grid you scroll the rows vertically and access the column horizontally

foreach(DataRow row in myDataSet.Tables(0).Rows)
{
   // At this point the row iterator point to a row 
   // where all the values in the schema columns are available
   // Indexing with the column name will result in related value 
   MessageBox.Show(row["D"].ToString();
}
于 2013-05-06T14:14:06.800 回答