2015-11-02 51 views
0

我使用foreach循環和內循環我宣佈數據行如何在foreach循環之外聲明datarow?

DataSet ds = Business.Site.GetSiteActiveModulesWithStatus(siteId);    
foreach (DataRow dr in ds.Tables[0].Rows) 

我如何能實現foreach循環超出這個數據行,我怎麼能使用循環而不是foreach循環?

+0

我想你需要一個關於C#,循環和一般控制語句+ ADO.NET的基本教程。如果你有一個確切的問題,請回來。我也不知道現在是什麼。 – mikus

回答

1

要循環的爲:

for(int i = 0; i < ds.Tables[0].Rows.Count; i++) 
{ 
    //To acess the row 
    DataRow row = ds.Tables[0].Rows[i]; 
} 

外供,接取特定的DataRow,你可以這樣做:

//Change 0 to other numbers to acess other rows 
DataRow row = ds.Tables[0].Rows[0]; 
0

要訪問環路的行變量之外,你簡單得外聲明它:

DataRow rowFound = null; 

for(int i = 0; i < ds.Tables[0].Rows.Count; i++) 
{ 
    var currentRow = ds.Tables[0].Rows[i]; 

    if(true /*To do: define some matching criteria*/) 
    { 
     rowFound = currentRow; 
    } 
} 

if(rowFound != null) 
{ 
    // We found some matching, what shall we do? 
} 

但你也可以寫相同的LINQish風格:

var rowFound = ds.Tables[0].AsEnumerable() 
          .Where(row => true /*To do: define some matching criteria*/) 
          .FirstOrDefault(); 

此答案中的所有代碼未經測試。