2013-10-22 26 views
1

我的當前代碼循環遍歷DataTable對象的特定列的所有行。我希望它只能循環到最後的第二個位置。我該怎麼做 ?如何修改我的代碼 - 如何循環到一個DataTable的第n行?

我知道這可以通過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; 
    } 
+1

您使用了標籤'for-loop'。這應該是一個提示。 :-) – LarsTech

+0

@LarsTech - 是的,我知道。但是,我不知道如何獲取行數,然後基於索引逐行迭代。那就是我需要幫助的地方。 – Steam

+0

如果這是你的意思,你可以直接訪問第n行而不循環。 dt.Rows [n-1] – Tarik

回答

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]

另外請注意,您可以

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

這是使用LINQ你的字符串中使用+=,可能無法以最快的速度爲循環:

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); 
+0

謝謝。它很好地知道多種解決方案。 – Steam

+0

當然,這是真的! – Kaf

相關問題