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

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


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<string, Action> which will allow you to easily map string -> method call like this:

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


This might be a good place for "EnvironmentSettings"-class.

public class EnvironmentSettings
{
public string ConnectionString { get; set; }
public string Query { get; set; } //rename this and chance the type to match usage.
}


And usage

Dictionary<string, EnvironmentSettings> environmentSettings = new Dictionary<string, EnvironmentSettings>()
{
{ "environment1", new EnvironmentSettings { ConnectionString="connectionstring1", Query=query1 } },
{ "environment2", new EnvironmentSettings { ConnectionString="connectionstring1", Query=query2 } },
{ "environment3", new EnvironmentSettings { ConnectionString="connectionstring2", Query=query1 } }
};

foreach (var environment in Environments)
{
var settings = environmentSettings[environment];
FillList(settings.ConnectionString, settings.Query);
}


Environment settings should probably be loaded somewhere else, and they should be accessed trough some more sophisticated method. See this answer and ConfigurationManager documentation