简体   繁体   English

C#逻辑可在选中复选框时实现foreach循环

[英]C# logic to implement foreach loop when check box is checked

I have a checkBox in my Windows application called "Continuous". 我在Windows应用程序中有一个名为“ Continuous”的复选框。 When user checks this and clicks "Process" button, application will process all the items in the listBox. 当用户选中此项并单击“处理”按钮时,应用程序将处理listBox中的所有项目。 However if user does not check this box it will only process the first one in the list. 但是,如果用户未选中此框,它将仅处理列表中的第一个。

In my Process method I want to write an if condition to check the checkBox checked and execute the foreach loop otherwise execute just the first item. 在我的Process方法中,我想编写一个if条件来检查选中的checkBox并执行foreach循环,否则仅执行第一项。

Here is my code 这是我的代码

private void btnProcess_Clicl()
{

  bool bDone = false;

  while(!bDone)
  {

    LoadList(); //This will load the list from database into listBox

    if(listBox.items.Count > 0)
    {
      ProcessList();
    }

    if(!chkBox.Checked)
      bDone = true;

  }

}

I've implement the foreach loop to process list in ProcessList() method. 我已经实现了foreach循环来处理ProcessList()方法中的列表。 Is there anyway to avoid executing LoadList() method from executing if the user checks continuous checkBox? 无论如何,如果用户检查了连续的checkBox,是否有可能避免执行LoadList()方法? LoadList() will populate the listBox from database. LoadList()将从数据库填充listBox。

do something like this 做这样的事情

if( chkBox.Checked )
    ProcessList();
else
    ProcessOne();

Write the functions to do what you want 编写函数以执行所需的操作

update 更新

to avoid duplicating the processing code you could do something like 为了避免重复处理代码,您可以执行以下操作

public void ProcessList()
{
    foreach( var item in list )
        ProcessOne( item );
}

Factoring is your friend. 保理是您的朋友。

void ProcessList(int start, int count) {
    for (int i=start; i < start + count; i++) {
        ProcessItem(i);
    }
}

void ProcessItem(int i) { // your code here
}

private void btnProcess_Click() {
   if (IsContinuous) {
      ProcessList(0, list.Count);
   }
   else {
       ProcessItem(0);
   }
}

private bool IsContinuous { get { return chkBox.Checked; } }

This will work for you but I don't especially like it since I think Process should be part of the list data structure itself and not my UI. 这将为您工作,但我不是特别喜欢它,因为我认为Process应该是列表数据结构本身而不是UI的一部分。 Model (and View) and Control should be separate (if possible). 模型(和视图)和控件应该分开(如果可能)。

    Boolean doAllItems = chkBox.Checked;
    foreach(Object something in collection)
    {
        DoWork(something);
        if(!doAllItems)
            break;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM