数据集中特定列的所有行

本文关键字:数据集 集中 数据 | 更新日期: 2023-09-27 18:12:23

我有一个数据集,如下所示:

| 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,但它不存在。

数据集中特定列的所有行

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"));

在内部网格中,垂直滚动行,水平访问列

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();
}