2010-08-16 143 views
0

分支是複選框列表類型,但在循環時,它僅添加一個項目,而我想將所有「li」存儲在branch_id中,並且稍後想要回顧它爲什麼不在branch_is中添加所有項目。有沒有其他的選項可以將所有這些添加到變量branch_id中。foreach循環問題

  foreach (ListItem li in branch.Items) 
       { 
        if(li.Selected) 
        { 

         List<int> branch_id = new List<int>(); 
         branch_id.Add(Convert.ToInt32(li.Value)); 

        } 
       } 

回答

1

試試這個

List<int> branch_id = new List<int>(); 
foreach (ListItem li in branch.Items) 
{ 
    if(li.Selected) 
    { 
      branch_id.Add(Convert.ToInt32(li.Value)); 
    } 
} 

或者這一個,如果你使用的是.NET 3.5或更高版本,可以使用LINQ

List<int> branch_id = branch.Items.Where(li=>li.Selected).Select(li=>li.Value).ToList(); 
+0

噢,我的上帝一個新的對象被創建的Y – NoviceToDotNet 2010-08-16 05:14:48

0

你不需要再次初始化List<int> branch_id = new List<int>();

如果初始化它將爲branch_id創建一個新實例並清除所有當前值。

foreach (ListItem li in branch.Items) 
       { 
        if(li.Selected) 
        { 

         List<int> branch_id = new List<int>(); // during each time it loops it create new memory and you can't save all the values 
         branch_id.Add(Convert.ToInt32(li.Value)); 

        } 
       } 



so do 

List<int> branch_id = new List<int>(); 
foreach (ListItem li in branch.Items) 
       { 
        if(li.Selected) 
        { 


         branch_id.Add(Convert.ToInt32(li.Value)); 

        } 
       } 
0

我曾經wrote about an extension method,讓我簡化與LINQ的選擇:每次

var branch_id = branch.Items.WhereSelected().Select(i => Convert.ToInt32(i.Value)).ToList() 
+0

我使用2.O多數民衆贊成Ÿ它不」我認爲這是我的工作。 你的回答也很有幫助。 謝謝 – NoviceToDotNet 2010-08-16 06:04:18