Pauli
Pauli

Reputation: 363

C# - Automatic creation of objects with config list/file

My intention is to create a bunch of objects of a class City at the launch of the application by using a config file.

The class City has some properties like CityName, Population etc.

Basically the config file delivers a List<string> with all city names like the following:

public List<string> configCityNames = new List<string> {
    "New York", "Chicago", "Boston", "San Francisco", "Miami", "etc."
};

Also I want to store all City objects in a repository to easily access them from somewhere else.

How can I automatically create one City object for each of the config List items? Maybe with a loop in an init function of the model? For me is especially unclear how to handle the object/variable names? When all objects are created in a loop, won't they have all the same object/variable name?

Upvotes: 0

Views: 281

Answers (2)

chomba
chomba

Reputation: 1451

You could define an extension method to generate a List of City from a List of string

public class City
{
    public string Name { get; set; }
    public string Population { get; set; }
}

public static class Mappings
{
    public static List<City> ConvertToCity(this List<string> names)
    {
        List<City> cities = new List<City>();

        foreach (string name in names)
        {
            cities.Add(new City { Name = name });
        }
        return cities;
    }
}

You can then use the extension method as follows:

class Program
{
    static void Main()
    {
        List<string> configCityNames = new List<string> {
            "New York", "Chicago", "Boston", "San Francisco", "Miami", "etc."
        };

        List<City> cities = configCityNames.ConvertToCity();
    }
}

Upvotes: 1

Mechanic
Mechanic

Reputation: 89

Something like this I have often used a dictionary to keep track of the values while knowing a Key (as long as the key is unique - if it is not unique you could use a list of KeyValuePairs)

For example, I would use the city name as a key to the dictionary and create an instance of the City class and set the variables. It will allow you to loop through them since the Dictionary values are IEnumerable but still allow you to find the city by name if needed.

class City
{
    public string CityName { get; set; }
    public int Population { get; set; }
}

class Program
{
    public static List<string> configCityNames = new List<string> 
    {
        "New York", "Chicago", "Boston", "San Francisco", "Miami", "etc."
    };


    static void Main(string[] args)
    {
        var cities = new Dictionary<string, City>();
        foreach(var cityName in configCityNames)
            cities.Add(cityName, new City() { CityName = cityName });

        foreach (var city in cities.Values)
            Console.WriteLine(city.CityName);
    }
}

Upvotes: 1

Related Questions