开发者

foreach loop issue

开发者 https://www.devze.com 2023-01-11 21:51 出处:网络
branch is of checkbox list type, but while looping through this it adds only one item while i want to store all \"li\" in branch_id and want to retrive later why it\'s not adding all in branch_is. is

branch is of checkbox list type, but while looping through this it adds only one item while i want to store all "li" in branch_id and want to retrive later why it's not adding all in branch_is. is there any other option which can add all this to variable branch_id.

          foreach (ListItem li in branch.Items) 
                {
                    if(li开发者_JS百科.Selected)
                    {

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

                    }
                } 


Try this one

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

Or this one if you are using .Net 3.5 or higher and can use LINQ

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


you no need for initializing the List<int> branch_id = new List<int>(); again.

If you initialize it will create a new instance for the branch_id and clear all the present value.

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

                    }
                } 


I once wrote about an extension method that allows me to simplify the selection with LINQ:

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

精彩评论

暂无评论...
验证码 换一张
取 消