如何修改我的代码 - 如何循环到数据表的第 n 行

本文关键字:数据表 修改 何修改 我的 代码 何循环 循环 | 更新日期: 2023-09-27 18:36:23

我当前的代码循环遍历DataTable对象特定列的所有行。我希望它只循环到倒数第二个位置。我该怎么做?

我知道这可以通过 for 循环而不是我的 foreach 来完成。 但是,我不知道如何获取行数,然后根据索引逐行迭代。这就是我需要帮助的地方。

    public void Main()
    {
        OleDbDataAdapter oleDA = new OleDbDataAdapter();
        DataTable dt = new DataTable();
        DataColumn col = null;
        DataRow row = null;
        string strCols = null;
        oleDA.Fill(dt, Dts.Variables["ExecuteSQLTask_ResultSet"].Value);
        col = dt.Columns["AColumInDataTable"];
        foreach (DataRow row_ in dt.Rows)
        {
            row = row_;
            strCols = strCols + row[col.Ordinal].ToString() + ", ";
        }
        strCols = strCols.Substring(0, strCols.Length - 2);
        MessageBox.Show("Rows of a column contain - " + strCols);
        Dts.TaskResult = (int)ScriptResults.Success;
    }

如何修改我的代码 - 如何循环到数据表的第 n 行

foreach更改为

for(int i=0; i<dt.Rows.Count-1;i++)
{
   var row = dt.Rows[i]
   strCols += row[col.Ordinal].ToString() + ", ";
}

根据您的编辑,您可以使用 dt.Rows.Count 获得行数。 若要获取倒数第二行,请使用 dt.Rows[dt.Rows.Count-2]

另请注意,您可以在字符串上使用+=

    for (int loop = 0; loop <= dt.Rows.Count - 2; loop++)
    {
        row = dt.Rows[loop];
        //your code
    }
这是

使用Linq的,可能没有for循环那么快:

string strCols = "";
dt.AsEnumerable().Take(dt.Rows.Count-2)
        .ToList()
        .ForEach(r=> strCols += "," + r.Field<string>(col.Ordinal));

使用string.Join()方法:

var results = dt.AsEnumerable()
                .Take(dt.Rows.Count-2)
                .Select(r=>r.Field<string>(col.Ordinal)).ToArray();
string strCols = string.Join(",", results);