2010-08-16 153 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