c # – Create a method to use a foreach instead of multiple

The first step is to look at the repeated code and then copy a single into a method.
In this case, a method name might seem CreateDataTable.

What are the points in common?

  • A Combo box who has checked the elements.
  • Obtain a IQueryable or Enumerable Depending on what is returned by the where clause
  • Create a list of the text value of each item marked
  • Create a Data table using ToStringDataTable (parameters

Since input and writing are equal, this makes it much easier to refactor in a method. The question then is what input and what output?

Input = Combo box, output = `DataTable & # 39 ;. This gives the signature of the necessary method:

DataTable CreateDataTable (ComboBox cbo) {

Now put in those lines that repeat and change the *State to cbo and instead of assigning the Data table single he came back the result of ToStringDataTable (parameters).

DataTable CreateDataTable (ComboBox cbo) {

var checkedItems = cbo.CheckBoxItems.Where (x => x.Checked);
List ParameterList = New List();
foreach (var i in checkedItms) {
parameter.Add (i.Text);

return ToStringDataTable (parameters);

Now clean the original method:

public class refactor {
private void BtnLoadReport_Click (sender object, EventArgs e)
var db = new SQLDataMgr ();

var designStatusParameters = CreateDataTable (cboDesignStatus);
var shopStatusParameters = CreateDataTable (cboShopStatus);
var customerTypeParameters = CreateDataTable (cboCustomerType);
var customerParameters = CreateDataTable (cboCustomer);
var resellerParameters = CreateDataTable (cboReseller);
var stateParameters = CreateDataTable (cboState);
var projectManagerParameters = CreateDataTable (cboProjectManager);
var salesRepresentativeParameters = CreateDataTable (cboSalesRepresentative);
// Rest of the method.

This could be further improved by using some additional LINQ strings if the elements returned by the where clause support them.


List parameters = cbo.CheckBoxItems.Where (x => x.Checked) .Select (x => x.Text) .ToList ();

What would simplify the method even more:

DataTable CreateDataTable (ComboBox cbo) {

List ParameterList = List parameters = cbo.CheckBoxItems.Where (x => x.Checked) .Select (x => x.Text) .ToList ();

return ToStringDataTable (parameters);