1

我当前的代码循环遍历 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;
    }
4

3 回答 3

3

改变你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]

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

于 2013-10-22T19:08:02.000 回答
2

这是使用 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);
于 2013-10-22T19:32:13.763 回答
2
    for (int loop = 0; loop <= dt.Rows.Count - 2; loop++)
    {
        row = dt.Rows[loop];
        //your code
    }
于 2013-10-22T19:16:32.600 回答