HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Iterating through list and calling method with different parameters for each item

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
itemiteratingmethodeachwithdifferentforthroughandlist

Problem

I am iterating over a list of environments but calling the same method each time. The only difference is the parameters are changing depending on what environment it is. The result so far is similar to the code below, i know this is not great but cant find a better way to solve it. Any ideas?

foreach (var environment in Environments)
        {
            if(environment == "environment1")
            {
                FillList("connectionstring1", query1);
            }
            else if (environment == "environment2")
            {
                FillList("connectionstring1", query2);
            }
            else if (environment == "environment3")
            {
                FillList("connectionstring2", query1);
            }
        }

Solution

The second parameter has the same value twice (query1) the first parameter also has the same value twice ("connectionstring1"), this means you can remove 1 if statement if you create 2 variables with initial values like this:

foreach (var environment in Environments)
{
    string connectionString = "connectionstring1";
    var query = query1;
    if (environment == "environment2")
    {
        query = query2;
    }
    else if (environment == "environment3")
    {
        connectionString = "connectionstring2";
    }
    FillList(connectionString, query);
}


Another option would be to add Dictionary which will allow you to easily map string -> method call like this:

Dictionary dictionary = new Dictionary
{
    ["environment1"] = () => FillList("connectionstring1", query1),
    ["environment2"] = () => FillList("connectionstring1", query2),
    ["environment3"] = () => FillList("connectionstring2", query1)
};
foreach (var environment in Environments)
{
    dictionary[environment].Invoke();
}

Code Snippets

foreach (var environment in Environments)
{
    string connectionString = "connectionstring1";
    var query = query1;
    if (environment == "environment2")
    {
        query = query2;
    }
    else if (environment == "environment3")
    {
        connectionString = "connectionstring2";
    }
    FillList(connectionString, query);
}
Dictionary<string, Action> dictionary = new Dictionary<string, Action>
{
    ["environment1"] = () => FillList("connectionstring1", query1),
    ["environment2"] = () => FillList("connectionstring1", query2),
    ["environment3"] = () => FillList("connectionstring2", query1)
};
foreach (var environment in Environments)
{
    dictionary[environment].Invoke();
}

Context

StackExchange Code Review Q#154605, answer score: 5

Revisions (0)

No revisions yet.