Creating method to use one foreach instead multiple











up vote
1
down vote

favorite












I'm working with C#, and I have working code where I repeated same code every line, and that's because I'm creating list, conversions, extracting data, etc.



I have multiple foreach clauses, multiple lists, multiple conversions of list to datatables. My question is, what can I do to refactor this in order to have clean code?



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

List<string> DesignStatusList = new List<string>();
List<string> ShopStatusList = new List<string>();
List<string> CustomerTypeList = new List<string>();
List<string> CustomerList = new List<string>();
List<string> ResellerList = new List<string>();
List<string> StateList = new List<string>();
List<string> ProjectManagerList = new List<string>();
List<string> SalesRepresentativeList = new List<string>();


var checkedDesignStatus = cboDesignStatus.CheckBoxItems.Where(x => x.Checked);
var checkedShopStatus = cboShopStatus.CheckBoxItems.Where(x => x.Checked);
var checkedCustomerType = cboShopStatus.CheckBoxItems.Where(x => x.Checked);
var checkedCustomer = cboShopStatus.CheckBoxItems.Where(x => x.Checked);
var checkedReseller = cboShopStatus.CheckBoxItems.Where(x => x.Checked);
var checkedState = cboShopStatus.CheckBoxItems.Where(x => x.Checked);
var checkedProjectManager = cboShopStatus.CheckBoxItems.Where(x => x.Checked);
var checkedSalesRepresentative = cboShopStatus.CheckBoxItems.Where(x => x.Checked);

foreach (var i in checkedDesignStatus)
{
DesignStatusList.Add(i.Text);
}
foreach (var i in checkedShopStatus)
{
ShopStatusList.Add(i.Text);
}
foreach (var i in checkedCustomerType)
{
CustomerTypeList.Add(i.Text);
}

foreach (var i in checkedCustomer)
{
CustomerList.Add(i.Text);
}
foreach (var i in checkedReseller)
{
ResellerList.Add(i.Text);
}
foreach (var i in checkedState)
{
StateList.Add(i.Text);
}
foreach (var i in checkedProjectManager)
{
ProjectManagerList.Add(i.Text);
}
foreach (var i in checkedSalesRepresentative)
{
SalesRepresentativeList.Add(i.Text);
}
DataTable designStatusParameters = ToStringDataTable(DesignStatusList);
DataTable shopStatusParameters = ToStringDataTable(ShopStatusList);
DataTable customerTypeParameters = ToStringDataTable(CustomerTypeList);
DataTable customerParameters = ToStringDataTable(CustomerList);
DataTable resellerParameters = ToStringDataTable(ResellerList);
DataTable stateParameters = ToStringDataTable(StateList);
DataTable projectManagerParameters = ToStringDataTable(ProjectManagerList);
DataTable salesRepresentativerParameters = ToStringDataTable(SalesRepresentativeList);


}









share|improve this question









New contributor




user186592 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
















  • 1




    Welcome to Code Review! Please tell us, what does this code accomplish? Also make that the title of the question — see How to Ask. Furthermore, you should ensure that you include enough context so that we can make sense of this code and give you good advice.
    – 200_success
    yesterday










  • (Please specify in every code you create what it is to accomplish, using the best mechanisms provided by the language or development environment of choice.)
    – greybeard
    20 hours ago















up vote
1
down vote

favorite












I'm working with C#, and I have working code where I repeated same code every line, and that's because I'm creating list, conversions, extracting data, etc.



I have multiple foreach clauses, multiple lists, multiple conversions of list to datatables. My question is, what can I do to refactor this in order to have clean code?



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

List<string> DesignStatusList = new List<string>();
List<string> ShopStatusList = new List<string>();
List<string> CustomerTypeList = new List<string>();
List<string> CustomerList = new List<string>();
List<string> ResellerList = new List<string>();
List<string> StateList = new List<string>();
List<string> ProjectManagerList = new List<string>();
List<string> SalesRepresentativeList = new List<string>();


var checkedDesignStatus = cboDesignStatus.CheckBoxItems.Where(x => x.Checked);
var checkedShopStatus = cboShopStatus.CheckBoxItems.Where(x => x.Checked);
var checkedCustomerType = cboShopStatus.CheckBoxItems.Where(x => x.Checked);
var checkedCustomer = cboShopStatus.CheckBoxItems.Where(x => x.Checked);
var checkedReseller = cboShopStatus.CheckBoxItems.Where(x => x.Checked);
var checkedState = cboShopStatus.CheckBoxItems.Where(x => x.Checked);
var checkedProjectManager = cboShopStatus.CheckBoxItems.Where(x => x.Checked);
var checkedSalesRepresentative = cboShopStatus.CheckBoxItems.Where(x => x.Checked);

foreach (var i in checkedDesignStatus)
{
DesignStatusList.Add(i.Text);
}
foreach (var i in checkedShopStatus)
{
ShopStatusList.Add(i.Text);
}
foreach (var i in checkedCustomerType)
{
CustomerTypeList.Add(i.Text);
}

foreach (var i in checkedCustomer)
{
CustomerList.Add(i.Text);
}
foreach (var i in checkedReseller)
{
ResellerList.Add(i.Text);
}
foreach (var i in checkedState)
{
StateList.Add(i.Text);
}
foreach (var i in checkedProjectManager)
{
ProjectManagerList.Add(i.Text);
}
foreach (var i in checkedSalesRepresentative)
{
SalesRepresentativeList.Add(i.Text);
}
DataTable designStatusParameters = ToStringDataTable(DesignStatusList);
DataTable shopStatusParameters = ToStringDataTable(ShopStatusList);
DataTable customerTypeParameters = ToStringDataTable(CustomerTypeList);
DataTable customerParameters = ToStringDataTable(CustomerList);
DataTable resellerParameters = ToStringDataTable(ResellerList);
DataTable stateParameters = ToStringDataTable(StateList);
DataTable projectManagerParameters = ToStringDataTable(ProjectManagerList);
DataTable salesRepresentativerParameters = ToStringDataTable(SalesRepresentativeList);


}









share|improve this question









New contributor




user186592 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
















  • 1




    Welcome to Code Review! Please tell us, what does this code accomplish? Also make that the title of the question — see How to Ask. Furthermore, you should ensure that you include enough context so that we can make sense of this code and give you good advice.
    – 200_success
    yesterday










  • (Please specify in every code you create what it is to accomplish, using the best mechanisms provided by the language or development environment of choice.)
    – greybeard
    20 hours ago













up vote
1
down vote

favorite









up vote
1
down vote

favorite











I'm working with C#, and I have working code where I repeated same code every line, and that's because I'm creating list, conversions, extracting data, etc.



I have multiple foreach clauses, multiple lists, multiple conversions of list to datatables. My question is, what can I do to refactor this in order to have clean code?



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

List<string> DesignStatusList = new List<string>();
List<string> ShopStatusList = new List<string>();
List<string> CustomerTypeList = new List<string>();
List<string> CustomerList = new List<string>();
List<string> ResellerList = new List<string>();
List<string> StateList = new List<string>();
List<string> ProjectManagerList = new List<string>();
List<string> SalesRepresentativeList = new List<string>();


var checkedDesignStatus = cboDesignStatus.CheckBoxItems.Where(x => x.Checked);
var checkedShopStatus = cboShopStatus.CheckBoxItems.Where(x => x.Checked);
var checkedCustomerType = cboShopStatus.CheckBoxItems.Where(x => x.Checked);
var checkedCustomer = cboShopStatus.CheckBoxItems.Where(x => x.Checked);
var checkedReseller = cboShopStatus.CheckBoxItems.Where(x => x.Checked);
var checkedState = cboShopStatus.CheckBoxItems.Where(x => x.Checked);
var checkedProjectManager = cboShopStatus.CheckBoxItems.Where(x => x.Checked);
var checkedSalesRepresentative = cboShopStatus.CheckBoxItems.Where(x => x.Checked);

foreach (var i in checkedDesignStatus)
{
DesignStatusList.Add(i.Text);
}
foreach (var i in checkedShopStatus)
{
ShopStatusList.Add(i.Text);
}
foreach (var i in checkedCustomerType)
{
CustomerTypeList.Add(i.Text);
}

foreach (var i in checkedCustomer)
{
CustomerList.Add(i.Text);
}
foreach (var i in checkedReseller)
{
ResellerList.Add(i.Text);
}
foreach (var i in checkedState)
{
StateList.Add(i.Text);
}
foreach (var i in checkedProjectManager)
{
ProjectManagerList.Add(i.Text);
}
foreach (var i in checkedSalesRepresentative)
{
SalesRepresentativeList.Add(i.Text);
}
DataTable designStatusParameters = ToStringDataTable(DesignStatusList);
DataTable shopStatusParameters = ToStringDataTable(ShopStatusList);
DataTable customerTypeParameters = ToStringDataTable(CustomerTypeList);
DataTable customerParameters = ToStringDataTable(CustomerList);
DataTable resellerParameters = ToStringDataTable(ResellerList);
DataTable stateParameters = ToStringDataTable(StateList);
DataTable projectManagerParameters = ToStringDataTable(ProjectManagerList);
DataTable salesRepresentativerParameters = ToStringDataTable(SalesRepresentativeList);


}









share|improve this question









New contributor




user186592 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











I'm working with C#, and I have working code where I repeated same code every line, and that's because I'm creating list, conversions, extracting data, etc.



I have multiple foreach clauses, multiple lists, multiple conversions of list to datatables. My question is, what can I do to refactor this in order to have clean code?



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

List<string> DesignStatusList = new List<string>();
List<string> ShopStatusList = new List<string>();
List<string> CustomerTypeList = new List<string>();
List<string> CustomerList = new List<string>();
List<string> ResellerList = new List<string>();
List<string> StateList = new List<string>();
List<string> ProjectManagerList = new List<string>();
List<string> SalesRepresentativeList = new List<string>();


var checkedDesignStatus = cboDesignStatus.CheckBoxItems.Where(x => x.Checked);
var checkedShopStatus = cboShopStatus.CheckBoxItems.Where(x => x.Checked);
var checkedCustomerType = cboShopStatus.CheckBoxItems.Where(x => x.Checked);
var checkedCustomer = cboShopStatus.CheckBoxItems.Where(x => x.Checked);
var checkedReseller = cboShopStatus.CheckBoxItems.Where(x => x.Checked);
var checkedState = cboShopStatus.CheckBoxItems.Where(x => x.Checked);
var checkedProjectManager = cboShopStatus.CheckBoxItems.Where(x => x.Checked);
var checkedSalesRepresentative = cboShopStatus.CheckBoxItems.Where(x => x.Checked);

foreach (var i in checkedDesignStatus)
{
DesignStatusList.Add(i.Text);
}
foreach (var i in checkedShopStatus)
{
ShopStatusList.Add(i.Text);
}
foreach (var i in checkedCustomerType)
{
CustomerTypeList.Add(i.Text);
}

foreach (var i in checkedCustomer)
{
CustomerList.Add(i.Text);
}
foreach (var i in checkedReseller)
{
ResellerList.Add(i.Text);
}
foreach (var i in checkedState)
{
StateList.Add(i.Text);
}
foreach (var i in checkedProjectManager)
{
ProjectManagerList.Add(i.Text);
}
foreach (var i in checkedSalesRepresentative)
{
SalesRepresentativeList.Add(i.Text);
}
DataTable designStatusParameters = ToStringDataTable(DesignStatusList);
DataTable shopStatusParameters = ToStringDataTable(ShopStatusList);
DataTable customerTypeParameters = ToStringDataTable(CustomerTypeList);
DataTable customerParameters = ToStringDataTable(CustomerList);
DataTable resellerParameters = ToStringDataTable(ResellerList);
DataTable stateParameters = ToStringDataTable(StateList);
DataTable projectManagerParameters = ToStringDataTable(ProjectManagerList);
DataTable salesRepresentativerParameters = ToStringDataTable(SalesRepresentativeList);


}






c#






share|improve this question









New contributor




user186592 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




user186592 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited 21 hours ago









Jamal

30.2k11115226




30.2k11115226






New contributor




user186592 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked yesterday









user186592

141




141




New contributor




user186592 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





user186592 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






user186592 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








  • 1




    Welcome to Code Review! Please tell us, what does this code accomplish? Also make that the title of the question — see How to Ask. Furthermore, you should ensure that you include enough context so that we can make sense of this code and give you good advice.
    – 200_success
    yesterday










  • (Please specify in every code you create what it is to accomplish, using the best mechanisms provided by the language or development environment of choice.)
    – greybeard
    20 hours ago














  • 1




    Welcome to Code Review! Please tell us, what does this code accomplish? Also make that the title of the question — see How to Ask. Furthermore, you should ensure that you include enough context so that we can make sense of this code and give you good advice.
    – 200_success
    yesterday










  • (Please specify in every code you create what it is to accomplish, using the best mechanisms provided by the language or development environment of choice.)
    – greybeard
    20 hours ago








1




1




Welcome to Code Review! Please tell us, what does this code accomplish? Also make that the title of the question — see How to Ask. Furthermore, you should ensure that you include enough context so that we can make sense of this code and give you good advice.
– 200_success
yesterday




Welcome to Code Review! Please tell us, what does this code accomplish? Also make that the title of the question — see How to Ask. Furthermore, you should ensure that you include enough context so that we can make sense of this code and give you good advice.
– 200_success
yesterday












(Please specify in every code you create what it is to accomplish, using the best mechanisms provided by the language or development environment of choice.)
– greybeard
20 hours ago




(Please specify in every code you create what it is to accomplish, using the best mechanisms provided by the language or development environment of choice.)
– greybeard
20 hours ago










1 Answer
1






active

oldest

votes

















up vote
3
down vote













First step is to look at the repeated code then copy an single into a method.
In this case a could method name would seem to be CreateDataTable.



What are the commonalities?




  • A ComboBox that has checked items.

  • Get an IQueryable or IEnumerable depending on which is returned by the where clause

  • Creates a list of the text value from each checked item

  • Creates a DataTable using ToStringDataTable(parameters


Since the type in and type out is all the same, this makes it much easier to refactor out into a method. The question then is what input and what output?



Input = ComboBox, output = `DataTable'. This give the method signature needed:



DataTable CreateDataTable(ComboBox cbo) {
}


Now put in those lines that are repeated and change the *Status to cbo and instead of assigning the DataTable just return the result of ToStringDataTable(parameters).



DataTable CreateDataTable(ComboBox cbo) {

var checkedItems = cbo.CheckBoxItems.Where(x => x.Checked);
List<string> parameterList = new List<string>();
foreach (var i in checkedItms) {
parameter.Add(i.Text);
}

return ToStringDataTable(parameters);
}


Now clean up the original method:



public class Refactor {
private void BtnLoadReport_Click(object sender, 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 chains if the items returned by the where clause supports them.



Example:



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


which would simplifying the method even further:



DataTable CreateDataTable(ComboBox cbo) {

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

return ToStringDataTable(parameters);
}





share|improve this answer





















    Your Answer





    StackExchange.ifUsing("editor", function () {
    return StackExchange.using("mathjaxEditing", function () {
    StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
    StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
    });
    });
    }, "mathjax-editing");

    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "196"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });






    user186592 is a new contributor. Be nice, and check out our Code of Conduct.










    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f209238%2fcreating-method-to-use-one-foreach-instead-multiple%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    3
    down vote













    First step is to look at the repeated code then copy an single into a method.
    In this case a could method name would seem to be CreateDataTable.



    What are the commonalities?




    • A ComboBox that has checked items.

    • Get an IQueryable or IEnumerable depending on which is returned by the where clause

    • Creates a list of the text value from each checked item

    • Creates a DataTable using ToStringDataTable(parameters


    Since the type in and type out is all the same, this makes it much easier to refactor out into a method. The question then is what input and what output?



    Input = ComboBox, output = `DataTable'. This give the method signature needed:



    DataTable CreateDataTable(ComboBox cbo) {
    }


    Now put in those lines that are repeated and change the *Status to cbo and instead of assigning the DataTable just return the result of ToStringDataTable(parameters).



    DataTable CreateDataTable(ComboBox cbo) {

    var checkedItems = cbo.CheckBoxItems.Where(x => x.Checked);
    List<string> parameterList = new List<string>();
    foreach (var i in checkedItms) {
    parameter.Add(i.Text);
    }

    return ToStringDataTable(parameters);
    }


    Now clean up the original method:



    public class Refactor {
    private void BtnLoadReport_Click(object sender, 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 chains if the items returned by the where clause supports them.



    Example:



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


    which would simplifying the method even further:



    DataTable CreateDataTable(ComboBox cbo) {

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

    return ToStringDataTable(parameters);
    }





    share|improve this answer

























      up vote
      3
      down vote













      First step is to look at the repeated code then copy an single into a method.
      In this case a could method name would seem to be CreateDataTable.



      What are the commonalities?




      • A ComboBox that has checked items.

      • Get an IQueryable or IEnumerable depending on which is returned by the where clause

      • Creates a list of the text value from each checked item

      • Creates a DataTable using ToStringDataTable(parameters


      Since the type in and type out is all the same, this makes it much easier to refactor out into a method. The question then is what input and what output?



      Input = ComboBox, output = `DataTable'. This give the method signature needed:



      DataTable CreateDataTable(ComboBox cbo) {
      }


      Now put in those lines that are repeated and change the *Status to cbo and instead of assigning the DataTable just return the result of ToStringDataTable(parameters).



      DataTable CreateDataTable(ComboBox cbo) {

      var checkedItems = cbo.CheckBoxItems.Where(x => x.Checked);
      List<string> parameterList = new List<string>();
      foreach (var i in checkedItms) {
      parameter.Add(i.Text);
      }

      return ToStringDataTable(parameters);
      }


      Now clean up the original method:



      public class Refactor {
      private void BtnLoadReport_Click(object sender, 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 chains if the items returned by the where clause supports them.



      Example:



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


      which would simplifying the method even further:



      DataTable CreateDataTable(ComboBox cbo) {

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

      return ToStringDataTable(parameters);
      }





      share|improve this answer























        up vote
        3
        down vote










        up vote
        3
        down vote









        First step is to look at the repeated code then copy an single into a method.
        In this case a could method name would seem to be CreateDataTable.



        What are the commonalities?




        • A ComboBox that has checked items.

        • Get an IQueryable or IEnumerable depending on which is returned by the where clause

        • Creates a list of the text value from each checked item

        • Creates a DataTable using ToStringDataTable(parameters


        Since the type in and type out is all the same, this makes it much easier to refactor out into a method. The question then is what input and what output?



        Input = ComboBox, output = `DataTable'. This give the method signature needed:



        DataTable CreateDataTable(ComboBox cbo) {
        }


        Now put in those lines that are repeated and change the *Status to cbo and instead of assigning the DataTable just return the result of ToStringDataTable(parameters).



        DataTable CreateDataTable(ComboBox cbo) {

        var checkedItems = cbo.CheckBoxItems.Where(x => x.Checked);
        List<string> parameterList = new List<string>();
        foreach (var i in checkedItms) {
        parameter.Add(i.Text);
        }

        return ToStringDataTable(parameters);
        }


        Now clean up the original method:



        public class Refactor {
        private void BtnLoadReport_Click(object sender, 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 chains if the items returned by the where clause supports them.



        Example:



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


        which would simplifying the method even further:



        DataTable CreateDataTable(ComboBox cbo) {

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

        return ToStringDataTable(parameters);
        }





        share|improve this answer












        First step is to look at the repeated code then copy an single into a method.
        In this case a could method name would seem to be CreateDataTable.



        What are the commonalities?




        • A ComboBox that has checked items.

        • Get an IQueryable or IEnumerable depending on which is returned by the where clause

        • Creates a list of the text value from each checked item

        • Creates a DataTable using ToStringDataTable(parameters


        Since the type in and type out is all the same, this makes it much easier to refactor out into a method. The question then is what input and what output?



        Input = ComboBox, output = `DataTable'. This give the method signature needed:



        DataTable CreateDataTable(ComboBox cbo) {
        }


        Now put in those lines that are repeated and change the *Status to cbo and instead of assigning the DataTable just return the result of ToStringDataTable(parameters).



        DataTable CreateDataTable(ComboBox cbo) {

        var checkedItems = cbo.CheckBoxItems.Where(x => x.Checked);
        List<string> parameterList = new List<string>();
        foreach (var i in checkedItms) {
        parameter.Add(i.Text);
        }

        return ToStringDataTable(parameters);
        }


        Now clean up the original method:



        public class Refactor {
        private void BtnLoadReport_Click(object sender, 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 chains if the items returned by the where clause supports them.



        Example:



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


        which would simplifying the method even further:



        DataTable CreateDataTable(ComboBox cbo) {

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

        return ToStringDataTable(parameters);
        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered yesterday









        Richard

        462




        462






















            user186592 is a new contributor. Be nice, and check out our Code of Conduct.










            draft saved

            draft discarded


















            user186592 is a new contributor. Be nice, and check out our Code of Conduct.













            user186592 is a new contributor. Be nice, and check out our Code of Conduct.












            user186592 is a new contributor. Be nice, and check out our Code of Conduct.
















            Thanks for contributing an answer to Code Review Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            Use MathJax to format equations. MathJax reference.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f209238%2fcreating-method-to-use-one-foreach-instead-multiple%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Ellipse (mathématiques)

            Quarter-circle Tiles

            Mont Emei